在日常代码编程中,需要通过接口进行批量下载,由于依次批量下载单个文件比较打脑壳,所以选择了 在后端进行压缩文件之后下载压缩包。代码如下(转载于其他地方,不晓得哪里看见的了,如有侵权,联系就删):
1.创建将文件保存到本地临时路径的类。
/**
* @param
* @param fileUrl
* @param filePath
* @return void
* @author FeianLing
* @date 2019/9/16
* @desc 通过url请求将文件保存到本地
*/
public static void saveFile(String fileUrl, String filePath) throws IOException {
URL url = new URL(fileUrl);
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileUtils.copyURLToFile(url, file);
}
}
2.创建压缩下载接口:
/**
* 压缩下载接口
* @param id
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/downloadCompression")
public Result download(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
PageData pd = getPageData();
Result result = new Result();
List<PageData> fileList = new ArrayList<>();
if (pd.get("mids") != null) {
String mids = pd.get("mids").toString();//循环遍历mids
String[] split = mids.split(",");
for (String str : split) {
pd.put("mid", str);
List<PageData> pds = databaseService.findFileUrlList(pd);
if (pds.size() != 0) {
for (PageData pdc : pds) {
PageData filePd = new PageData();
String url = configService.getByKey("common.nginx.path") + "/" + pdc.getString("file_path") + "/" + pdc.getString("file_name_store");
filePd.put("fileName", pdc.get("file_name"));
String filePath = request.getSession().getServletContext().getRealPath("") + "/excel" + "/" + pdc.get("file_name");
FileUtil.saveFile(url, filePath);
filePd.put("filePath", filePath);
fileList.add(filePd);
}
}else {
result.setMsg("下载失败,文件不存在");
result.setSuccess(false);
}
}
//设置压缩包的名字
//解决不同浏览器压缩包名字含有中文时乱码的问题
String zipName = "download.zip";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename="+ zipName);
//设置压缩流:直接写入response,实现边压缩边下载
ZipOutputStream zipos =null;
try{
zipos=new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法
}catch(Exception e){
e.printStackTrace();
}
DataOutputStream os=null;
//循环将文件写入压缩流
int i = 0;
for (PageData pdd : fileList) {
i++;
String strc = pdd.getString("filePath");
File file = new File(strc);//要下载文件的路径
try{
//添加ZipEntry,并ZipEntry中写入文件流
//这里,加上i是防止要下载的文件有重名的导致下载失败fileName
zipos.putNextEntry(new ZipEntry(i + "." + String.valueOf(pdd.get("fileName"))));
os=new DataOutputStream(zipos);
InputStream is=new FileInputStream(file);
byte[] b = new byte[100];
int length = 0;
while((length = is.read(b))!= -1){
os.write(b, 0, length);
}
is.close();
zipos.closeEntry();
}catch(Exception e){
e.printStackTrace();
}
}
//关闭流
try {
os.flush();
os.close();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}