java批量下载网络文件输出成zip包
直接上代码
@PostMapping("/batchDownload")
@ApiOperation("网络批量下载")
public Result batchDownload(HttpServletResponse response, @RequestBody List<DownloadDto> strs) throws Exception {
List<DownloadDto> certificates = strs;
if (certificates==null){
throw new RenException("请先选择文件,在下载!");
}
//组装DownloadDto省略
String nTime = System.currentTimeMillis()+""; //获取当前时间戳
String filename = nTime + ".zip";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
int l = 0;
//循环下载
for (DownloadDto certificate: certificates) {
l+=1;
zos.putNextEntry(new ZipEntry(l + certificate.getFileName()));
String url = certificate.getUrlPath();
byte[] bytes = downloadUrlToByte(url);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.close();
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
File saveDri = new File(downloadFilePath);
if (!saveDri.exists()){
saveDri.mkdirs();
}
// 保存到的文件路径
File files = new File(downloadFilePath + filename);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(files));
out.write(bos.toByteArray());
out.close();
return new Result();
}
public byte[] readInputStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
try {
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.flush();
} catch (IOException e) {
e.printStackTrace();
// log.error("readInputStream IOException", e);
}
byte[] data = baos.toByteArray();
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
// log.error("IOException", e);
}
return data;
}
/**
* 根据文件链接把文件下载下来并且转成字节码
*/
public byte[] downloadUrlToByte(String downloadUrl) {
byte[] data = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
URL url = new URL(downloadUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
if (conn.getResponseCode() == 200) {
data = readInputStream(is);
} else {
data = null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
// log.error("downloadUrlToByte MalformedURLException", e);
} catch (IOException e) {
e.printStackTrace();
// log.error("downloadUrlToByte IOException", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
// log.error("IOException", e);
}
conn.disconnect();
}
return data;
}
博主精品推荐:
1.微软发布激进支出计划:大举投资满足 AI 服务需求
2.国家网信办等七部门联合公布《生成式人工智能服务管理暂行办法》,8 月 15 日起施行
3.马斯克宣布人工智能公司 xAI 正式成立,旨在“了解宇宙的真实本质
4.月份中国采购经理指数公布 制造业采购经理指数继续回升
推荐关注微信公众号:带你了解最前沿的科技资讯: