2021-10-31springboot文件上传

首先在配置文件中对文件保存路径进行设置

#指定文件上传的目录
photo:
           files:
             dir: D:\protect\thymeleaf\photos

然后在控制层对文件路径使用注解的方式进行注入

@Value("${photo.files.dir}")
    private String realpath;

上传头像方法抽取

 /*抽取方法:上传头像方法*/
    private String uploadPhoto(MultipartFile img, String originalFilename) throws IOException {
        String fileNamePrefix = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());
        String fileNameSuffix = originalFilename.substring(img.getOriginalFilename().lastIndexOf("."));
        String newFileName = fileNamePrefix+fileNameSuffix;
        img.transferTo(new File(realpath,newFileName));//transfreTo为图片传输方法
        return newFileName;
    }

另外在表单中类型要注意

enctype="multipart/form-data"
#application.yal文件中
spring:
  web:
    resources:
      static-locations: classpath:/static/,file:${photo.files.dir} #暴露哪些资源可以被项目名访问
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值