Loading

SpringBoot上传文件

application.yaml

配置上传路经,其实写在哪都行无所谓,就是引入配置文件,@Values注解赋值

web:
  #绝对路经
  upload-path: D://test/

spring
  servlet:
    multipart:
      enabled: true
      # 单个文件的最大上限
      max-file-size: 1024MB
      #单个请求的文件总大小上限
      max-request-size: 1024MB
  web:
    resources:
      static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}

Controller

@PostMapping("/file")
    public ResultBody updateFile(@RequestParam("file") MultipartFile file){
        try {
            if (file.isEmpty()){
                return ResultBody.error("上传文件为空");
            }
            if (file.getSize() > MAX_POST_SIZE){
                return ResultBody.error("文件必须小于10MB");
            }
            return fileService.uploadFile(file);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBody.error(e.getMessage());
        }
    }

Service

public ResultBody updateFile(int id, MultipartFile file) {
        try {
            String format = this.path_sdf.format(new Date());

            //随机命名
            String name = fileUtil.getNewRandomFileName(file.getOriginalFilename());
            
            File imgFolder = new File(fileUtil.getAbsoluteImgRootPath() + format);
            if (!imgFolder.isDirectory()) {
                imgFolder.mkdirs();
            }
            file.transferTo(new File(imgFolder, name));
            String cover = fileUtil.getRelativeImgRootPath() + format + name;
            return ResultBody.success(success);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultBody.error("失败");
        }
    }

工具类

@Component
public class FileUtil {
    @Value("${web.upload-path}")
    public String uploadPath;

    private String getRelativeFilePath(String type) {
        return "uploads" + File.separator + type + File.separator;
    }
    public String getAbsoluteUploadsPath(){
        return uploadPath + "uploads/";
    }
    public String getAbsoluteFilePath(String type) {
        return uploadPath + getRelativeFilePath(type);
    }

    public String getAbsoluteImgRootPath() {
        return getAbsoluteFilePath("img");
    }


    public String getRelativeImgRootPath() {
        return getRelativeFilePath("img");
    }

    public String getNewRandomFileName(String oldName) {
        return UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."));
    }

    public String getNewFileName(String oldName, String newName) {
        return newName + oldName.substring(oldName.lastIndexOf("."));
    }
}
posted @ 2023-09-11 11:43  AmorFati404  阅读(51)  评论(0)    收藏  举报