package com.yangche.utils; import javax.servlet.http.HttpServletResponse; import java.io.*; public class UploadDownUtil { /** *文件下載 * @param path * @param response * @return */ public static HttpServletResponse download(String path, HttpServletResponse response) { try { // path是指欲下載的文件的路徑。 File file = new File(path); // 取得文件名。 String filename = file.getName(); // 取得文件的后綴名。 String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 以流的形式下載文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 設置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; } }
maven依賴(可能會和tomcat自帶的沖突,看情況,如果沒有這個依賴再添加)
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency>
controller層的代碼(前端直接訪問這個方法即可直接下載對應的文件!可以自己拿瀏覽器訪問試試)
package com.yangche.controller; import com.yangche.utils.UploadDownUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.net.URL; @Controller public class FileController { @RequestMapping(path="/api/file/download") @ResponseBody public void fileDownload(HttpServletRequest request, HttpServletResponse response){ URL xmlpath = this.getClass().getClassLoader().getResource("file/123.xlsx"); //通過這種方式獲得文件的路徑 String path = xmlpath.getPath(); UploadDownUtil.download(path, response); } }
如圖:我把前端要下載的文件放到了這個目錄下

注意:有時候把文件放到自己的項目中下載后打不開,我的項目就是這種情況,一個excel打不開,但是如果文件不在項目中,直接引用電腦上的文件,就是可以打開的,目前不清楚是什么原因導致的,望不吝賜教。
