1.定义文件上传路径(通过properties文件指定路径)
解析properties文件
@ConfigurationProperties(prefix = "file") // 前缀名
@PropertySource(value = "fileUpload-dev.properties") // properties文件路径 默认application.properties
@Component
2.文件上传过程
2-1.Controller层指定文件接收类型(MultipartFile file)
2-2.获取原始文件名,file.getOriginalFileName(); 转换成自定义文件名。
2-3.File uploadFile = new File(“文件上传路径”);
2-4.创建文件上传目录
if(uploadFile.getParentFile != null){ uploadFile.getParentFile.mkdirs(); }
2-5.定义输入、输出流
InputStream inputStream = file.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(uploadFile);
2-6.复制输入流到输出流
IOUtils.copy(inputStream, fileOutputStream);
2-7.关闭输出流
fileOutputStream.flush();
fileOutputStream.close();
3.映射静态资源文件,让文件实现可以通过浏览器访问
3-1.添加配置类,实现WebMvcConfigurer的addResourceHandlers方法
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("file:/Users/xxxx/Documents/foodie/") // 映射文件上传路径
.addResourceLocations("classpath:/META-INF/resources/"); // 映射swagger2
}
3-2.保存图片信息到数据库
防止前端图片缓存加入参数?t=时间戳
注:保存上传文件服务路径时,记得前面添加http://或者https://,不然会导致报错ERR_UNKOWN_URL_SCHEME。