| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package com.template.controller;
- import com.alibaba.fastjson.JSONObject;
- import com.template.common.utils.FileUtil;
- import com.template.model.result.CommonResult;
- 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 {
- @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, "/home/nginx/html/image");
- // String imgFilePath = "/home/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="192.168.161.224:12345/"+fileNameWithPath;
- // response.getWriter().println(url);
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("url",url);
- return CommonResult.ok(jsonObject);
- }
- }
|