好像目前是不可能的。有人做过吗?我只有几个 PDF 文件,我想将它们添加到 zip 文件夹中!
1 回答
很抱歉这篇文章中缺少链接:这是我在 stackoverflow 上的第一篇文章,正如错误消息所说,“[我] 需要至少 10 个声誉才能发布超过 2 个链接。”
要下载 pdf(或任何二进制文件),您可以使用它xhr.responseType = "arraybuffer"
来获取原始内容(警告:这在 IE 6-9 中不起作用,更多内容见下文)。您不能使用 jQuery 来执行此操作(但请参阅 github.com/jquery/jquery/pull/1525),但原始 xhr 查询或任何处理二进制数据的 ajax 库都可以。例如 github.com/Stuk/jszip-utils 上的 jszip-utils(免责声明:我是这个库的贡献者)。
我最近在 JSZip 文档上工作 (github.com/Stuk/jszip/pull/114),并添加了一个您正在尝试做的示例。拉取请求仍在等待中,所以这里是临时网址:http ://dduponchel.github.io/temp-jszip-documentation/documentation/examples/downloader.html
合并后它应该位于http://stuk.github.io/jszip/documentation/examples/downloader.html 。
这是代码:
此函数使用JSZipUtils
并将结果包装到 ajQuery.Deferred
但任何可以返回 ArrayBuffer 或 Uint8Array 的库都可以使用。
/**
* Fetch the content, add it to the JSZip object
* and use a jQuery deferred to hold the result.
* @param {String} url the url of the content to fetch.
* @param {String} filename the filename to use in the JSZip object.
* @param {JSZip} zip the JSZip instance.
* @return {jQuery.Deferred} the deferred containing the data.
*/
function deferredAddZip(url, filename, zip) {
var deferred = $.Deferred();
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
deferred.reject(err);
} else {
zip.file(filename, data, {binary:true});
deferred.resolve(data);
}
});
return deferred;
}
这是主要功能,它使用 FileSaver.js 作为 polyfill saveAs
:
var $form = $("#download_form").on("submit", function () {
var zip = new JSZip();
var deferreds = [];
// find every checked item
$(this).find(":checked").each(function () {
var url = $(this).data("url");
var filename = url.replace(/.*\//g, "");
deferreds.push(deferredAddZip(url, filename, zip));
});
// when everything has been downloaded, we can trigger the dl
$.when.apply($, deferreds).done(function () {
var blob = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(blob, "example.zip");
}).fail(function (err) {
// handle the error here
});
return false;
});
关于 IE 6-9 的注意事项:jszip 和 jszip-utils 支持 IE 6-9,但没有 ArrayBuffer/Uint8Array,性能会很差。
编辑:链接 JSZip Utils GitHub:https ://github.com/Stuk/jszip-utils