springboot实现文件上传

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。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值