@ResponseBody @RequestMapping(value="/downloadFile") public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{ //解決亂碼問題 String path = request.getParameter("path"); String fileName = request.getParameter("fileName"); path = MyUtils.isRandomCode(path); fileName = MyUtils.isRandomCode(fileName); try { String filePath = path+fileName; //高速瀏覽器以附件形式下載 //不同瀏覽器的編碼不同,對中文進行編碼,下載時輸出名稱是文件名 response.setHeader("Content-Disposition","attachment;filename="+fileName); //獲取文件的mimetype,如123.txt,他的mimetype就是 txt ,下載時,就以 txt 格式下載 String mimeType = fileName.substring(fileName.lastIndexOf(".") + 1); //獲取文件后綴,比如是 txt 文件,就是以txt格式下載 //設置響應的 mimetype response.setContentType(mimeType); //獲取response 輸出流,用來輸出文件 ServletOutputStream out = response.getOutputStream(); //接下來進行讀取,以輸入流的形式讀取 FileInputStream in = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int len = 0; while ((len=in.read(buffer))!=-1){ out.write(buffer,0,len); } in.close(); } catch (Exception e) { System.out.println("下載錯誤!"); } }
這里有一個工具類,就是前端傳過來的參數有可能會亂碼,所以要判斷一下是否亂碼,有亂碼的話就處理一下
package com.zhouhe.modules.api.util; import java.io.UnsupportedEncodingException; /** * 自定義工具類 * @Author zhouhe * @Date 2019/11/15 11:54 */ public class MyUtils { /** * 判斷是否是亂碼,亂碼的話進行處理,不亂碼直接返回 * @param code * @return */ public static String isRandomCode(String code) throws UnsupportedEncodingException { if (!XUtil.isEmpty(code)) { //判斷是亂碼 (GBK包含全部中文字符;UTF-8則包含全世界所有國家需要用到的字符。) if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(code))) { code = new String(code.getBytes("ISO-8859-1"), "utf-8"); //轉碼UTF8 } } return code; } }
前端可以使用 window.location.href=請求路徑,比如:
注意:
不能使用ajax請求后台下載文件,否則會有問題:
ajax請求只是個“字符型”的請求,即請求的內容是以文本類型存放的。文件的下載是以二進制形式進行的,ajax沒法解析后台返回的文件流,所以無法處理二進制流response輸出來下載文件,可以在瀏覽器中的network里面查看訪問的地址,找到response一欄就看見 后台返回的數據:
解決方法:
文件直接下載(不需要傳遞參數),可以使用 < a href="/media">點擊下載Excel < /a>
前端需要傳遞參數(如excel),可以在綁定方法里面 window.location.href=url
文件預覽:
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception { File f = new File(filePath); if (!f.exists()) { response.sendError(404, "File not found!"); return; } BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; response.reset(); // 非常重要 if (isOnLine) { // 在線打開方式 URL u = new URL("file:///" + filePath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); // 文件名應該編碼成UTF-8 } else { // 純下載方式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + f.getName()); } OutputStream out = response.getOutputStream(); while ((len = br.read(buf)) > 0) out.write(buf, 0, len); br.close(); out.close(); }
要注意在路徑前加了file:///,否則會報錯 java.net.MalformedURLException: unknown protocol: e
還有一點就是中文下載或者帶空格的話可能會有問題,會出現中文亂碼或者變成___,而空格會被截斷,處理方式如下:
response.setHeader("Content-Disposition","attachment;filename="+fileName);
換成
response.setHeader("Content-Disposition","attachment; filename=\"" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + "\"");