UploadServlet.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.template.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.template.common.utils.FileUtil;
  4. import com.template.model.result.CommonResult;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.Part;
  13. import java.io.File;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.nio.file.Files;
  17. @RestController
  18. @RequestMapping("/auto/upload")
  19. public class UploadServlet {
  20. @Value("${image-url}")
  21. private String imageUrl;
  22. @PostMapping("/save")
  23. protected CommonResult doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  24. // 获取文件内容
  25. Part filePart = request.getPart("file");
  26. InputStream fileContent = filePart.getInputStream();
  27. String fileNameWithPath = FileUtil.getFileNameWithPath() + ".jpg";
  28. // FileUtil.makeDirs(fileNameWithPath, "E://image3");
  29. // String imgFilePath = "E://image3/" + fileNameWithPath;
  30. FileUtil.makeDirs(fileNameWithPath, "/usr/local/nginx/html/image");
  31. String imgFilePath = "/usr/local/nginx/html/image/" + fileNameWithPath;
  32. // 上传图片
  33. Files.copy(fileContent,new File(imgFilePath).toPath());
  34. // 保存文件到指定目录
  35. // String fileName = filePart.getSubmittedFileName();
  36. // OutputStream out = new FileOutputStream(imgFilePath);
  37. // byte[] buffer = new byte[1024];
  38. // int bytesRead;
  39. // while ((bytesRead = fileContent.read(buffer)) != -1) {
  40. // out.write(buffer, 0, bytesRead);
  41. // }
  42. // out.close();
  43. String url=imageUrl+fileNameWithPath;
  44. // response.getWriter().println(url);
  45. JSONObject jsonObject = new JSONObject();
  46. jsonObject.put("url",url);
  47. return CommonResult.ok(jsonObject);
  48. }
  49. }