Springboot图片上传功能实现 文件上传

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("图片上传失败");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值