1、配置上传路径
web:
upload-path: E:/img/ #自定义文件上传路径
multipart:
maxRequestSize: 2Mb #设置所有文件最大内存
maxFileSize: 2Mb #设置单个文件最大内存
2、springboot配置类中添加配置
@Value("${web.upload-path}")
private String uploadFiltPath; // 保存上传文件的路径
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//上传的图片在D盘下的OTA目录下,访问路径如:http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
//其中OTA表示访问的前缀。"file:D:/OTA/"是文件真实的存储路径
registry.addResourceHandler("/img/**").addResourceLocations("file:" + uploadFiltPath);
super.addResourceHandlers(registry);
}
3、上传工具类
/**
* 文件上传工具包
*/
public class FileUtils {
/**
* @param file 文件
* @param path 文件存放路径
* @param fileName 源文件名
* @return
*/
public static boolean upload(MultipartFile file, String path, String fileName) {
// 生成新的文件名
//String realPath = path + "/" + FileNameUtils.getFileName(fileName);
//使用原文件名
String realPath = path + "/" + fileName;
File dest = new File(realPath);
//判断文件父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
//保存文件
file.transferTo(dest);
return true;
} catch (IllegalStateException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
4、controller
@RestController
public class UploadController {
@Value("${web.upload-path}")
private String path;
/**
* @param file 要上传的文件
* @return
*/
@PassToken
@PostMapping("/upload")
public Result upload(@RequestParam("file") MultipartFile file) {
if (FileUtils.upload(file, path, file.getOriginalFilename())) {
// 上传成功,给出页面提示
return ResultGenerator.genSuccessResult("/img/" + file.getOriginalFilename());
} else {
throw new ServiceException("图片上传失败");
}
}
}