一、前言
有个需求就是,将第三方的网络图片或文件,打包成压缩包下载,下载过程中,文件不存本地,下载完成之后,打包成压缩包,相关代码如下:
二、实现
前端ajax
var form = $("<form></form>").attr("action", "/batchDownload/xxx").attr("method", "post");
form.appendTo('body').submit().remove();
需通过表单的形式提交才能触发下载。
后端代码
public void batchDownload(HttpServletResponse response) throws Exception {
List<DownloadDto> certificates = Lists.newArrayList();
//组装DownloadDto省略
String nTime = DateUtil.getTime(); //获取当前时间戳
String filename = nTime + ".zip";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
//循环下载
for (DownloadDto certificate: certificates) {
zos.putNextEntry(new ZipEntry(StringUtils.join(xxx,"-",xxx,".pdf")));
String url = certificate.getUrl();
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);// 设置文件名
OutputStream os = response.getOutputStream();
os.write(bos.toByteArray());
os.close();
}
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) {
log.error("readInputStream IOException", e);
}
byte[] data = baos.toByteArray();
try {
is.close();
baos.close();
} catch (IOException e) {
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) {
log.error("downloadUrlToByte MalformedURLException", e);
} catch (IOException e) {
log.error("downloadUrlToByte IOException", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
log.error("IOException", e);
}
conn.disconnect();
}
return data;
}