話不多說,直接上代碼......
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; /*** * 將文件內容響應到瀏覽器 */ public class DownloadUtil { // 字符編碼格式 private static String charsetCode = "utf-8"; /** * 文件的內容類型 */ private static String getFileContentType(String name){ String result = ""; String fileType = name.toLowerCase(); if (fileType.endsWith(".png")) { result = "image/png"; } else if (fileType.endsWith(".gif")) { result = "image/gif"; } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) { result = "image/jpeg"; } else if(fileType.endsWith(".svg")){ result = "image/svg+xml"; }else if (fileType.endsWith(".doc")) { result = "application/msword"; } else if (fileType.endsWith(".xls")) { result = "application/x-excel"; } else if (fileType.endsWith(".zip")) { result = "application/zip"; } else if (fileType.endsWith(".pdf")) { result = "application/pdf"; } else { result = "application/octet-stream"; } return result; } /** * 下載文件 * @param path 文件的位置 * @param fileName 自定義下載文件的名稱 * @param resp http響應 * @param req http請求 */ public static void downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req){ try { File file = new File(path); /** * 中文亂碼解決 */ String type = req.getHeader("User-Agent").toLowerCase(); if(type.indexOf("firefox")>0 || type.indexOf("chrome")>0){ /** * 谷歌或火狐 */ fileName = new String(fileName.getBytes(charsetCode), "iso8859-1"); }else{ /** * IE */ fileName = URLEncoder.encode(fileName, charsetCode); } // 設置響應的頭部信息 resp.setHeader("content-disposition", "attachment;filename=" + fileName); // 設置響應內容的類型 resp.setContentType(getFileContentType(fileName)+"; charset=" + charsetCode); // 設置響應內容的長度 resp.setContentLength((int) file.length()); // 輸出 outStream(new FileInputStream(file), resp.getOutputStream()); } catch (Exception e) { System.out.println("執行downloadFile發生了異常:" + e.getMessage()); } } /** * 基礎字節數組輸出 */ private static void outStream(InputStream is, OutputStream os) { try { byte[] buffer = new byte[10240]; int length = -1; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); os.flush(); } } catch (Exception e) { System.out.println("執行 outStream 發生了異常:" + e.getMessage()); } finally { try { os.close(); } catch (IOException e) { } try { is.close(); } catch (IOException e) { } } } }
使用。。( springboot項目 )