分享一个文件下载的工具类,代码如下,已经测试过,都可以使用。
package com.example.demo.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; @Component public class DownloadUtil { private static Logger logger = LoggerFactory.getLogger(DownloadUtil.class); /** * 文件下载方法 * @param response * @param filePath * @param encode */ public static void download(HttpServletResponse response, String filePath, String encode) { response.setContentType("text/html;charset=" + encode); BufferedInputStream bis = null; BufferedOutputStream bos = null; String downLoadPath = filePath; try { File file = new File(downLoadPath); long fileLength = file.length(); String fileName = file.getName().split("\\.")[0]+"0."+file.getName().split("\\.")[1]; response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(encode), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(downLoadPath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { logger.error(e.getMessage()); } finally { if (bis != null) try { bis.close(); } catch (IOException e) { logger.error(e.getMessage()); } if (bos != null) try { bos.close(); } catch (IOException e) { logger.error(e.getMessage()); } } } /** * 以流的方式下载 * @param response * @param filePath * @param encode * @return response */ public static HttpServletResponse downloadStream(HttpServletResponse response, String filePath, String encode) { response.setContentType("text/html;charset=" + encode); try { // path是指欲下载的文件的路径 File file = new File(filePath); // 取得文件名 String filename = file.getName().split("\\.")[0]+"0."+file.getName().split("\\.")[1]; // 取得文件的后缀名 // String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 以流的形式下载文件 InputStream fis = new BufferedInputStream(new FileInputStream(filePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(encode), "ISO8859-1")); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { logger.error(ex.getMessage()); } return response; } /** * 下载本地文件 * @param response * @param filePath * @param encode */ public static void downloadLocal(HttpServletResponse response, String filePath,String encode) { response.setContentType("text/html;charset=" + encode); try { // 读到流中 InputStream inStream = new FileInputStream(filePath); // 文件的存放路径 // path是指欲下载的文件的路径 File file = new File(filePath); // 取得文件名 String fileName = file.getName().split("\\.")[0]+"0."+file.getName().split("\\.")[1]; // 设置输出的格式 response.reset(); response.setContentType("bin"); response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(encode), "ISO8859-1") + "\""); // 循环取出流中的数据 byte[] b = new byte[2048]; int len; StringBuffer sb = new StringBuffer(); while ((len = inStream.read(b)) > 0) { sb.append(new String(b)); response.getOutputStream().write(b, 0, len); response.getOutputStream().flush(); } inStream.close(); } catch (IOException e) { logger.error(e.getMessage()); } } public static void downFile(HttpServletResponse response, String filePath) { // String zipPath = path.split("/WEB-INF")[0] + "/zips/" + str; String name = filePath.split("/")[filePath.split("/").length-1]; //读取要下载的文件,保存到文件输入流 try { // 设置头部信息 response.setHeader( "Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8")); FileInputStream in = new FileInputStream(filePath); //创建输出流 OutputStream out = response.getOutputStream(); //创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; //循环将输入流中的内容读取到缓冲区当中 while((len=in.read(buffer))>0){ //输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } //关闭文件输入流 in.close(); //关闭输出流 out.close(); } catch (Exception e) { e.printStackTrace(); } } }