public static void writeToResponse(HttpServletRequest request, HttpServletResponse response, String directory, String filepath) throws Exception { if (directory.indexOf(":") != -1) {// windows下的絕對路徑 filepath = filepath.replace("/", "\\"); } else { // linux下絕對路徑 filepath = filepath.replace("\\", "/"); } File file = new File(filepath); if (!file.exists()) { throw new FileNotFoundException("文件未找到或已被移除!"); } String filename = file.getName(); response.setContentType("application/octet-stream; charset=utf-8"); // 不行再試這個: application/force-download String userAgent = request.getHeader("User-Agent"); byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8"); // name.getBytes("UTF-8")處理safari的亂碼問題 filename = new String(bytes, "ISO-8859-1"); // 各瀏覽器基本都支持ISO編碼 response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename)); // 文件名外的雙引號處理firefox的空格截斷問題 response.addHeader("Content-Length", String.valueOf(file.length())); InputStream in = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); byte[] buff = new byte[4096]; int len; while (((len = in.read(buff)) != -1)) { out.write(buff, 0, len); } in.close(); out.flush(); out.close(); }