UploadServlet.java 2.0 KB

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