java下载文件

tech2022-10-27  128

package com.chuangqi.tools; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * \* Created with IntelliJ IDEA. * \* @author: xiyue * \* Date: 2020/4/16 * \* Time: 10:19 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ public class DownloadUtils { //下载文件调用的本地方法 public static boolean downLoadFile(HttpServletResponse response, String name, File file) { if (file.exists()) { try { name = new String(name.getBytes("UTF-8"), "ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 设置强制下载不打开 response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment;fileName=" + name); byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream outputStream = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { outputStream.write(buffer, 0, i); i = bis.read(buffer); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } return false; } }
最新回复(0)