package com.lianxi.demo85.controller;
import com.lianxi.demo85.Utils.UploadUtils;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
-
@author
*/
@Controller
@Api(tags = “上传文件至项目路径”,description = “上传文件至项目路径”)
public class UploadController {@ResponseBody
@PostMapping("/upload-file")
public Map<String,Object> upload(@RequestParam(“imgFile”) MultipartFile imgFile, HttpServletRequest request, HttpSession session) {
Map<String,Object> map = new HashMap<>();
if (imgFile.isEmpty()) {
// 设置错误状态码
map.put(“code”,“500”);
map.put(“message”,“上传失败,请选择文件”);
return map;
}
// 拿到文件名
String filename = imgFile.getOriginalFilename();
// 存放上传图片的文件夹
File fileDir = UploadUtils.getImgDirFile();
// 输出文件夹绝对路径 – 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
System.out.println(fileDir.getAbsolutePath());
try {
// 构建真实的文件路径
File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
System.out.println(newFile.getAbsolutePath());
// 上传图片到 -》 “绝对路径”
imgFile.transferTo(newFile);
map.put(“code”,“200”);
map.put(“message”,“上传成功!”);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
工具类:
package com.lianxi.demo85.Utils;
import java.io.File;
public class UploadUtils {
public final static String IMG_PATH_PREFIX = “static/upload/imgs”;
public static File getImgDirFile(){
// 构建上传文件的存放 “文件夹” 路径
String fileDirPath = new String(“src/main/resources/” + IMG_PATH_PREFIX);
File fileDir = new File(fileDirPath);
if(!fileDir.exists()){
// 递归生成文件夹
fileDir.mkdirs();
}
return fileDir;
}
}
##静态资源
spring.resources.static-locations=classpath:static/,file:static/