springboot文件上传到本地
application.yml
将文件上传到制定目录去:
filePath:
D:/Desktop/mow/upload
spring:
resources:
static-locations: classpath:static/**spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${filePath}
upload.java
@PostMapping("/uploadImgToLocal")
public String uploadImg(MultipartFile uploadFile, HttpServletRequest req){
//获取文件名
String fileName = uploadFile.getOriginalFilename();
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//重新生成文件名
fileName = UUID.randomUUID()+suffixName;
//添加日期目录
String format = sd.format(new Date());
//指定本地文件夹存储图片
String filePath = "D:/Desktop/mow/upload/"+format+"/";
File file = new File(filePath,fileName);
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
try {
//将图片保存到static文件夹里
file.createNewFile();
uploadFile.transferTo(new File(filePath+fileName));
return "http://"+req.getRemoteHost()+":"+req.getServerPort()+"/"+format+"/"+fileName;
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}