文件下载器:
import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.util.function.Consumer; import static com.keydak.base.utils.CloseUtil.close; @Slf4j public class DownloadUtil { public static void download(HttpServletResponse response, String srcFilePath, String targetName) { FileInputStream in = null; BufferedInputStream bis = null; try { in = new FileInputStream(srcFilePath); response.setContentType("application/octet-stream;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); response.setHeader("Content-Disposition", "attachment;fileName=" + targetName + ";filename*=utf-8''" + URLEncoder.encode(targetName, "UTF-8")); int available = in.available(); response.setHeader("Content-Length", String.valueOf(available)); // 发送给客户端的数据 OutputStream outputStream = response.getOutputStream(); byte[] buff = new byte[1024]; // 读取filename bis = new BufferedInputStream(in); int i = bis.read(buff); while (i != -1) { outputStream.write(buff, 0, buff.length); outputStream.flush(); i = bis.read(buff); } } catch (Exception e) { e.printStackTrace(); } finally { close(in); } } /** * 浏览器下载 * * @param response 响应流 * @param fileName 文件名 * @param consumer 流的处理 */ public static void download(HttpServletResponse response, String fileName, Consumer<OutputStream> consumer) { try { String targetName = fileName; response.setContentType("application/octet-stream;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(targetName, "UTF-8") + ";filename*=utf-8''" + URLEncoder.encode(targetName, "UTF-8")); // 发送给客户端的数据 OutputStream outputStream = response.getOutputStream(); if (consumer != null) { consumer.accept(outputStream); } } catch (Exception e) { log.error("下载失败:" + e.getMessage()); } } }
引用例子:
DownloadUtil.download(response, fileName, (stream) -> { try { List<*******> groups = new ArrayList<>(); groups.add(group); new ProjectXStreamFactory().getXStream().toXML(groups, stream); } catch (Exception e) { e.printStackTrace(); } finally { CloseUtil.close(stream); } });