package com.daling.util.file; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; /** * @author tanhq * 文件上传下载 */ public class FileUtil { /** * 文件下载 * @param response * @param request * @param filePath */ public static void downloadLocal(HttpServletResponse response, HttpServletRequest request, String filePath) { try { // 下载本地文件 String path = request.getSession().getServletContext().getRealPath(filePath); File file = new File(path); String fileName = file.getName(); // 读到流中 InputStream inStream = new FileInputStream(file); // 设置输出的格式 response.reset(); response.setContentType("bin"); response.addHeader("Content-Type","application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + new String(URLEncoder.encode(fileName,"UTF-8"))); // 循环取出流中的数据 byte[] b = new byte[100]; int len; while ((len = inStream.read(b)) > 0){ response.getOutputStream().write(b, 0, len); } inStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
转载于:https://my.oschina.net/u/3033132/blog/3035642