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:\develop\upload\
# ..... 省略其他無關配置
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拒絕訪問


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM