1. 将文件下载到文件夹中,打包zip放入浏览器
/*
* Copyright 2019 yifen7.com All right reserved. This software is the
* confidential and proprietary information of yifen7.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with yifen7.com.
*/
package com.yifenqi.zulin.biz.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
/**
* zip文件工具类
*
* @author zhangshiwei
* @since 2019-10-17 17:22:43
*/
@Slf4j
public class ZipUtil {
/**
* 把文件打成压缩包并保存在本地硬盘
*
* @param srcfiles 文件地址
* @param zipPath zip文件名称
*/
public static void zipFiles(List<String> srcfiles, String zipPath) {
byte[] buf = new byte[4096];
ZipOutputStream out = null;
try {
// 创建zip输出流
out = new ZipOutputStream(new FileOutputStream(zipPath));
// 循环将源文件列表添加到zip文件中
for (String url : srcfiles) {
File file = new File(url);
FileInputStream in = new FileInputStream(file);
String fileName = file.getName();
// 将文件名作为zip的Entry存入zip文件中
out.putNextEntry(new ZipEntry(fileName));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
}
catch (IOException e) {
log.info("e:{}", e.getMessage());
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
log.info("e:{}", e.getMessage());
}
}
}
}
/**
* 把文件打成压缩包并输出到客户端浏览器中
*
* @param request 请求信息
* @param response 响应信息
* @param srcFiles 文件地址
* @param downloadZipFileName 最终zip附件名称: xxx.zip
* @param fileBufferSize 读取缓存大小
*/
public static void zipFiles(HttpServletRequest request, HttpServletResponse response, List<String> srcFiles,
String downloadZipFileName, int fileBufferSize) {
log.info("zipFiles-downloadZipFileName:{} , fileBufferSize:{} byte", downloadZipFileName, fileBufferSize);
long start = System.currentTimeMillis();
byte[] buf = new byte[fileBufferSize];
try {
// Create the ZIP file
// ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
//--设置成这样可以不用保存在本地,再输出, 通过response流直接输出到客户端浏览器中
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
// Compress the files
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
downloadZipFileName = new String(downloadZipFileName.getBytes("GB2312"), "ISO-8859-1");
} else {
// 对文件名进行编码处理中文问题
downloadZipFileName = java.net.URLEncoder.encode(downloadZipFileName, "UTF-8");
downloadZipFileName = new String(downloadZipFileName.getBytes("UTF-8"), "GBK");
}
response.reset();
response.setCharacterEncoding("UTF-8");
// 不同类型的文件对应不同的MIME类型
response.setContentType("application/x-msdownload");
// inline在浏览器中直接显示,不提示用户下载
// attachment弹出对话框,提示用户进行下载保存本地
// 默认为inline方式
response.setHeader("Content-Disposition", "attachment;filename=" + downloadZipFileName);
for (String url : srcFiles) {
File file = new File(url);
FileInputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
String fileName = file.getName();
out.putNextEntry(new ZipEntry(fileName));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
log.info("下载zip完成-耗时:{} ms", System.currentTimeMillis() - start);
} catch (IOException e) {
log.info("e:{}", e.getMessage());
}
}
}
2. 将文件放入文件夹,将文件夹打包成zip,再把zip放入浏览器
/**
* 下载zip文件
*
* @param targetName 目标文件夹名称
* @param response 响应信息
*/
@Override
public void downloadZipFile(String targetName, HttpServletResponse response) {
long start = System.currentTimeMillis();
String folder = tempFilePath + targetName;
log.error("打包下载-{}-开始-folder:{}", targetName, folder);
try {
int fileBufferSize = CommConstant.FILE_BUFFER_SIZE_DEFAULT;
DictCode dictCode = dictCodeService.findByGroupAndCodeNoCache(CommConstant.FILE_BUFFER_SIZE,
CommonFlag.Y.getCode());
if (dictCode != null) {
fileBufferSize = Integer.valueOf(dictCode.getName());
}
if (StringUtils.isBlank(targetName)) {
response.getWriter().println("targetName is blank , please check targetName!");
return;
} else {
response.reset();
}
response.setContentType("application/ostet-stream");
// 告诉浏览器弹出下载对话框
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(targetName + ".zip", "UTF-8"));
// 准备压缩下载的文件夹
File folderFile = new File(folder);
if (!folderFile.exists() || !folderFile.isDirectory()) {
response.getWriter().println("folderFile is error , please check targetName!");
return;
}
// 准备输出的zip文件的名称
File zipFile = new File(folder + ".zip");
long start2 = System.currentTimeMillis();
new IOUtils(zipFile).zipFiles(folderFile);
log.info("压缩目标文件-耗时:{}", System.currentTimeMillis() - start2);
// 读取zip文件
InputStream ins = new FileInputStream(zipFile);
// 放到缓冲流里面
BufferedInputStream bins = new BufferedInputStream(ins);
// 获取文件输出IO流
OutputStream outs = response.getOutputStream();
// 读取目标文件,通过response将目标文件写到客户端
BufferedOutputStream bouts = new BufferedOutputStream(outs);
int bytesRead;
// 开始向网络传输文件流
byte[] zipBuffer = new byte[fileBufferSize];
while ((bytesRead = bins.read(zipBuffer, 0, fileBufferSize)) != -1) {
bouts.write(zipBuffer, 0, bytesRead);
}
// 这里一定要调用flush()方法
bouts.flush();
ins.close();
bins.close();
outs.close();
bouts.close();
log.error("下载-完成-文件大小:{} , fileBufferSize:{} byte , 耗时:{} ms", VehicleUtils.getFileSize(zipFile),
fileBufferSize, System.currentTimeMillis() - start);
boolean deleteDirResult = IOUtils.deleteDir(folderFile);
boolean deleteZipResult = IOUtils.deleteDir(zipFile);
log.error("下载-完成-删除本地文件夹:{},删除本地zip文件:{}", deleteDirResult, deleteZipResult);
} catch (Exception e) {
log.error("下载-{}-异常:{}", targetName, e);
}
}
3. 下载单个文件
/**
* 下载单个文件
*
* @param file 文件信息
* @param response 响应信息
*/
@Override
public void downloadFile(File file, HttpServletResponse response) {
long start = System.currentTimeMillis();
try {
int fileBufferSize = CommConstant.FILE_BUFFER_SIZE_DEFAULT;
DictCode dictCode = dictCodeService.findByGroupAndCodeNoCache(CommConstant.FILE_BUFFER_SIZE,
CommonFlag.Y.getCode());
if (dictCode != null) {
fileBufferSize = Integer.valueOf(dictCode.getName());
}
if (file == null) {
response.getWriter().println("file is null , please check file!");
return;
} else if (!file.exists() || file.isDirectory()) {
response.getWriter().println("file is error , please check file!");
return;
}
log.error("下载-{}-开始", file.getName());
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((file.getName()).getBytes("gb2312"), "ISO8859-1"));
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] car = new byte[fileBufferSize];
int l;
while ((l = in.read(car)) != -1) {
out.write(car, 0, l);
}
out.flush();
out.close();
in.close();
log.error("下载-完成-文件大小:{} , fileBufferSize:{} byte, 耗时:{} ms", VehicleUtils.getFileSize(file),
fileBufferSize, System.currentTimeMillis() - start);
boolean deleteResult = IOUtils.deleteDir(file);
log.error("下载-完成-删除本地文件:{}", deleteResult);
} catch (Exception e) {
log.error("下载-异常:{}", JSON.toJSON(e));
}
}