/** * 根据文件路径下载文件 * @param filePath * @throws DownLoadFileException */ public void downLoadFileTool(String filePath) { InputStream in = null; OutputStream out = null; String fileName = ""; try { File file = new File(filePath); //获取文件名称 fileName = file.getName(); // 判断文件是否存在 if (file.exists()) { //封装响应头 escapeResponse(response, request, fileName, file.length()); // 读取文件 in = new FileInputStream(file); out = response.getOutputStream(); // 创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; // 循环将输入流中的内容读取到缓冲区当中 while ((len = in.read(buffer)) > 0) { // 输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } out.flush(); } else { throw new DownLoadFileException(fileName + "文件下载失败!"); } } catch (Exception e) { log.error("", e); } finally { // 关闭文件输入流 if (in != null) { try { in.close(); } catch (IOException e) { log.error("", e); } } // 关闭输出流 if (out != null) { try { out.close(); } catch (IOException e) { log.error("", e); } } } } /** * 文件下载,拼装response头部信息 * * @param response * @param fileName * @param fileSize * @throws Exception */ public static void escapeResponse(HttpServletResponse response, HttpServletRequest request, String fileName, long fileSize) throws Exception { // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.reset(); response.setContentType(escapeContentType(request, fileName)); // 2.设置文件头:最后一个参数是设置下载文件名 addEscapeHeader(response, "Content-Disposition", escapeContentDisposition(fileName, request)); addEscapeHeader(response, "Content-Length", "" + fileSize); } private static void addEscapeHeader(HttpServletResponse response, String key, String value) { response.addHeader(key, value); } /** * 获取文件类型 * * @param request * @param fileName * @return */ public static String escapeContentType(HttpServletRequest request, String fileName) { return request.getSession().getServletContext().getMimeType(fileName); } /** * 文件信息相关处理 * * @param fileName * @return * @throws Exception */ public static String escapeContentDisposition(String fileName, HttpServletRequest request) throws Exception { String agent = request.getHeader("User-Agent").toUpperCase(); //获得浏览器信息并转换为大写 if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) { //IE浏览器和Edge浏览器 fileName = URLEncoder.encode(fileName, "UTF-8"); } else { //其他浏览器 fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } fileName = "attachment;filename=" + fileName; return fileName; }
文件下载后端工具类
最新推荐文章于 2024-04-19 15:34:48 发布