利用springboot 重定向到靜態資源功能,下載一些文件文件


1、首先在配置文件添加項目外資源文件定位:

  

spring:
  web:
    resources:
      static-locations:  file:uploads/,classpath:static/    #手動設置項目外路徑uploads

 

2、我們可以在項目文件家中創建uploads文件夾,以后項目jar外面也有uploads文件夾,該文件夾放置我們要下載的文件:

    ,,,,

 

3、控制層定義 下載文件接口:

@Controller
public class DownClass {

    /**
     * 下載app
     * @param response
     * 解釋一下,我們在yml里面配置了地址uploads,並且也在項目的根路徑(直接在文件夾中,而不是IDEA工具里面)創建uploads/xxx.apk文件。
     */
    @RequestMapping("downApp")
    @ResponseBody
    public void Download(HttpServletResponse response,String version) {
        File directory = new File("");// 參數為空
        String courseFile = "";
        String fileName = "test-"+version+".apk";
        try {
            courseFile = directory.getCanonicalPath();
            System.out.println("path2: "+courseFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filepath = courseFile+"\\uploads\\" + fileName;
        File path = new File(filepath);
        if (!path.exists()) {
            System.out.println("找不到該文件:" + fileName);
            return;
        }else{
            try {
                response.sendRedirect("/" + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1、首先查詢該文件是否存在,文件名 + 版本號。

2、存在則利用response.sendRedirect("/" + fileName)  重定向到該文件。

其實就是靜態資源訪問罷。

 


免責聲明!

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



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