【java工具类】下载文件
FileUtil.java
/** * 下载文件 * @param file; * @param response */ public static void downloadFile(File file, HttpServletResponse response) { OutputStream os = null; try { os = response.getOutputStream(); String filePath = file.getName(); if(!file.exists()){ return; } response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment;filename=\"%s\"", URLEncoder.encode(filePath,"UTF-8"))); os.write(FileUtils.readFileToByteArray(file)); } catch (Exception e) { e.printStackTrace(); }finally{ IOUtils.closeQuietly(os); } }
调用:
File file = new File("G:/pic");
downloadFile(file, response);