springboot单文件上传到指定目录分类并返回访问路径

业务逻辑就不写service层了,方便展示.还没放到linux中测试....

问题解决

  • 使用ubuntu运行测试,并设置yml里的变量 path: /upload/出现了如下异常

    • FileNotFoundException: /upload/jpg/1595516455456eyes.jpg (No such file or directory)

    • 手动创建jpg子目录后出现新的异常

    • FileNotFoundException: /upload/jpg/1595516494684eyes.jpg (Permission denied)

    • 给/upload文件夹设置权限0777 上传成功,输入返回的url并成功访问

      {
        "code": 200,
        "msg": "操作成功",
        "data": "http://192.168.153.128:8086/archive/jpg/1595517483320eyes.jpg"
      }
      
    • 上传md格式的文件,成功创建了md目录,保存并返回url,输入url浏览器自动下载

  • 欢迎大佬题出更好意见

yml和配置类

yuan:
  file:
    root:
      ## 定义文件保存的路径
      path: D:developupload
# ..... 省略其他无关配置
spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB # 设置文件最大大小
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${yuan.file.root.path}")
    public String fileRootPath;

    /**
     * 资源映射:把请求的/archive/** 映射到该文件根路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/archive/**").addResourceLocations("file:" + fileRootPath);
    }
}

Controller层

@Api("文件操作相关")
@RestController
public class FileController {

    @Value("${yuan.file.root.path}")
    public String fileRootPath;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String filePath = ""; // 文件保存的位置
        String urlPath = "";// 文件web浏览路径
        Assert.isTrue(!file.isEmpty(), "文件为空");
        // 原始名 以 a.jpg为例
        String originalFilename = file.getOriginalFilename();
        // 获取后缀并拼接'/'用于分类,也可以用日期 例: suffix = "jpg/"
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1) + "/";
        // 加上时间戳生成新的文件名,防止重复 newFileName = "1595511980146a.jpg"
        String newFileName = System.currentTimeMillis() + originalFilename;
        filePath = fileRootPath + suffix + newFileName;
        System.out.println(filePath);
        try {
            File file1 = new File(filePath);
            if (!file1.exists()) file1.mkdirs(); // 要是目录不存在,创建一个
            file.transferTo(file1);              // 保存起来
            urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/archive/" + suffix + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(urlPath);
    }

}

结果




参考

springboot 如何上传图片文件到服务器的指定目录
文件上传报错java.io.FileNotFoundException拒绝访问

原文地址:https://www.cnblogs.com/somegenki/p/13369282.html