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) 重定向到該文件。
其實就是靜態資源訪問罷。