前段代码:
$scope.downloadZip = function () {
$http({
method: 'GET',
url: '后端地址',
responseType : "blob"
}).success(function (data) {
var zipName = "附件.zip";
var blob = new Blob([data]);
if (!!window.ActiveXObject || "ActiveXObject" in window){
window.navigator.msSaveBlob(blob, zipName);
}else{
var a = document.getElementById("downloadZipId");
if (a) {
a.parentNode.removeChild(a);
}
a = document.createElement("a");
a.id = "downloadZipId";
a.download = zipName;
a.href = URL.createObjectURL(blob);
a.style.display = "none";
document.body.appendChild(a);
a.click();
}
}).error(function (err) {
$scope.messageBox.showError(err.data.detail);
});
}
后端代码
public void downloadZip(HttpServletResponse response){
//设置响应头编码
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment;");
try (
//最外层的压缩包,还是往response的output里面输出
ZipOutputStream zipOut=new ZipOutputStream(response.getOutputStream());
){
zipOut.setMethod(ZipOutputStream.DEFLATED);
zipOut.putNextEntry(new ZipEntry("内部压缩包.zip"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (
//这里就是把第一个内部的压缩包放到byteArrayOutputStream中去了
ZipOutputStream zos2=new ZipOutputStream(byteArrayOutputStream);
){
//这里面内层压缩包的附件
zos2.setMethod(ZipOutputStream.DEFLATED);
zos2.putNextEntry(new ZipEntry("测试文件.txt"));
//替换成你本地文件地址
try (InputStream is = new FileInputStream("C:/Users/Desktop/新建文本文档.txt")){
int b;
byte[] buffer = new byte[1024];
while ((b=is.read(buffer))!=-1){
zos2.write(buffer,0,b);
}
zos2.flush();
}catch (Exception e){
}
}catch (Exception e){
}
//往最外部的压缩包里面写入
zipOut.write(byteArrayOutputStream.toByteArray());
zipOut.flush();
}catch (Exception e){
}
}