咱們只須要建立一個控制器(Controler)文件,即Controller目錄下的File_Download.java,其完整目錄以下:java
@Controller public class File_Download { //實現Spring Boot 的文件下載功能,映射網址爲/download @RequestMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { // 獲取指定目錄下的第一個文件 File scFileDir = new File("E://music_eg"); File TrxFiles[] = scFileDir.listFiles(); System.out.println(TrxFiles[0]); String fileName = TrxFiles[0].getName(); //下載的文件名 // 若是文件名不爲空,則進行下載 if (fileName != null) { //設置文件路徑 String realPath = "E://music_eg/"; File file = new File(realPath, fileName); // 若是文件名存在,則進行下載 if (file.exists()) { // 配置文件下載 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下載文件能正常顯示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 實現文件下載 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("Download the song successfully!"); } catch (Exception e) { System.out.println("Download the song failed!"); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; } }
這樣咱們就完成了Spring Boot的文件下載功能。瀏覽器
運行Spring Boot項目後,在瀏覽器中輸入:http://localhost:8080/download , 你會發現什麼?那就是你的瀏覽器已經開始下載E盤music_eg目錄下的某一個文件啦(前提是E盤中存在music_eg目錄,固然裏面還得有文件,本例僅做爲測試),以下圖所示:app