javascript - 将 Ajax 响应下载为 zip 文件?
问题描述
我正在尝试将多个图像下载为 zip 文件。当我使用 Azure blob 时,首先我列出了所有 blob,然后使用Archiver对其进行压缩,并使用管道函数将其发送到客户端。但是我将 zip 作为原始文件获取,并且没有下载。我正在使用 Node js + Express。服务器端脚本:
function zipURLs(urls, outStream) {
var zipArchive = archiver.create('zip');
async.eachLimit(urls, 3, function(url, done) {
console.log(url);
var stream = request.get(url);
stream.on('error', function(err) {
return done(err);
}).on('end', function() {
return done();
});
// Use the last part of the URL as a filename within the ZIP archive.
zipArchive.append(stream, { name : url.replace(/^.*\//, '') });
}, function(err) {
if (err) throw err;
zipArchive.finalize();
zipArchive.pipe(outStream);
});
}
var data = {};
data.blob_name = value;
console.log('downloading');
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'download/',
success: function(data) { console.log(data); }
外流是资源。所以我得到这样的数据: -
如何使用js直接下载为zip文件?
谢谢
解决方案
使用 ajax 下载文件有很多内容,首先您必须能够通过将 responseType 设置为 blob 来访问二进制数据(不是默认的文本)。然后你必须使用实际的方法来显示下载对话框,下面你可以看到带有下载属性技术的锚点。
jQuery.ajax({
url:'download/',
type:'POST',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields:{
responseType: 'blob'
},
success: function(data){
var anchor = document.getElementById('a');
var url = window.URL || window.webkitURL;
anchor.href = url.createObjectURL(data);
anchor.download = 'archive.zip';
document.body.append(anchor);
anchor.click();
setTimeout(function(){
document.body.removeChild(anchor);
url.revokeObjectURL(anchor.href);
}, 1};
},
error:function(){
}
});
需要 jQuery3+
推荐阅读
- angular - 如何解决“内容处置”标头在浏览器中显示为空
- mysql - Binary Log 在 MYSQL 数据流中的可用性:有什么缺点和优点?
- javascript - Vue CSS滚动时如何在屏幕上移动对象
- node.js - 有没有办法只将附加的 blob 内容传递给 blob 触发 Azure Function?
- python-3.x - Azure 函数 - 使用 python 代码解压缩受密码保护的文件
- python - 如何在具有特定键的列表中查找字典?
- regex - 使用 sed 替换 Apache vhosts 文件中的 SSL 证书
- python - 打印特定值
- javafx - 多个属性上的 ChangeListener
- java - 空对象参考 Android Studio