Spring boot图片上传

1.引入依赖
 <!-- io常用工具类 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
 2.yml配置
web:
  upload-path: D:\graduation-design-images\ # 图片保存位置
spring:
  web:
    resources:
      static-locations:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
3.静态资源处理配置
public class WebConfig implements WebMvcConfigurer {

    @Value("${web.upload-path}")
    private String fileSavePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        // addResourceHandler("/graduation-design-images/**")表示凡事以 /graduation-design-images/ 路径发起请求的,按照 addResourceLocations("file:"+fileSavePath)的路径进行映射
        registry.addResourceHandler("/graduation-design-images/**").addResourceLocations("file:"+fileSavePath);
    }
}
4.controller层
@Value("${web.upload-path}")
    private String uploadPath;

 @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile uploadFile) throws IOException {
        if(uploadFile.isEmpty()) return "参数为空";
        // 获取文件名
        String originName = uploadFile.getOriginalFilename();
        // 获取文件后缀
        String suffix = originName.substring(originName.lastIndexOf('.')+1);

        // 使用uuid作为新的文件名
        String fileName = UUID.randomUUID() + "." + suffix;

        // 在uploadPath路径下创建名为fileName的文件对象
        File file = new File(uploadPath,fileName);

        // 生成文件
        uploadFile.transferTo(file);
        return "上传成功";
    }
5.访问

localhost://127.0.0.1:端口/映射路径/文件.后缀

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值