package com.yanzuoguang.cloud.helper; import com.yanzuoguang.util.helper.HttpHelper; import com.yanzuoguang.util.helper.StringHelper; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; /** * HTTP文件 * * @author 颜佐光 */ public class HttpFileHelper extends HttpHelper { /** * 下载文件 * * @param serverFilePath 下载文件来源路径 * @param saveFileName 文件保存名称 * @param response 输出对象 * @throws IOException 异常信息 */ public static void localToDown(String serverFilePath, String saveFileName, HttpServletResponse response) throws IOException { //获取文件的长度 File file = new File(serverFilePath); if (StringHelper.isEmpty(saveFileName)) { File parentFile = file.getParentFile(); saveFileName = StringHelper.trimLeft(file.getAbsolutePath().substring(parentFile.getAbsolutePath().length()), "/"); } //设置文件输出类型 response.setContentType("application/octet-stream"); /**文件下载图片乱码处理**/ String fileName = URLEncoder.encode(saveFileName, "UTF-8"); // 设置下载的文件名 // 2.其他浏览器attachment;filename*=utf-8'zh_cn response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + fileName); response.setHeader("fileName", fileName); //设置输出长度 response.setHeader("Content-Length", String.valueOf(file.length())); response.addHeader("Access-Control-Expose-Headers", "Content-Disposition"); response.addHeader("Access-Control-Expose-Headers", "fileName"); ServletOutputStream bos = response.getOutputStream(); // 获取输入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(serverFilePath)); try { //输出流 byte[] buff = new byte[2048]; int readSize = 1; while (readSize > 0) { readSize = bis.read(buff, 0, buff.length); if (readSize > 0) { bos.write(buff, 0, readSize); } } } finally { bis.close(); } } }