| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package com.template.controller;
- import com.alibaba.fastjson.JSONObject;
- import com.template.common.utils.FileUtil;
- import com.template.model.result.CommonResult;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.Part;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.file.Files;
- @RestController
- @RequestMapping("/auto/upload")
- public class UploadServlet {
- @Value("${image-url}")
- private String imageUrl;
- @PostMapping("/save")
- protected CommonResult doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // 获取文件内容
- Part filePart = request.getPart("file");
- InputStream fileContent = filePart.getInputStream();
- String fileNameWithPath = FileUtil.getFileNameWithPath() + ".jpg";
- // FileUtil.makeDirs(fileNameWithPath, "E://image3");
- // String imgFilePath = "E://image3/" + fileNameWithPath;
- FileUtil.makeDirs(fileNameWithPath, "/usr/local/nginx/html/image");
- String imgFilePath = "/usr/local/nginx/html/image/" + fileNameWithPath;
- // 上传图片
- Files.copy(fileContent,new File(imgFilePath).toPath());
- // 保存文件到指定目录
- // String fileName = filePart.getSubmittedFileName();
- // OutputStream out = new FileOutputStream(imgFilePath);
- // byte[] buffer = new byte[1024];
- // int bytesRead;
- // while ((bytesRead = fileContent.read(buffer)) != -1) {
- // out.write(buffer, 0, bytesRead);
- // }
- // out.close();
- String url=imageUrl+fileNameWithPath;
- // response.getWriter().println(url);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("url",url);
- return CommonResult.ok(jsonObject);
- }
- }
|