下面是使用JSZip (代码示例)压缩文件的一个非常简单的示例
let fileInput;
document.addEventListener("DOMContentLoaded", async function () {
fileInput = document.getElementById("file");
});
function zip() {
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async function (e) {
const zip = new JSZip();
zip.file(file.name, e.target.result);
const content = await zip.generateAsync({
type: "base64"
});
createDownloadLink(content, "signed.zip");
};
reader.onerror = function (e) {
console.log("Error : " + e.type);
};
reader.readAsBinaryString(file);
}
function createDownloadLink(content, fileName) {
var link = document.getElementById("downloadLink");
if (link) {
link.remove();
}
link = document.createElement("a");
link.innerHTML = "Download zip";
link.setAttribute("href", "data:application/zip;base64," + content);
link.setAttribute("download", fileName);
link.setAttribute("id", "downloadLink");
document.getElementById("downloadLinkPanel").appendChild(link)
}如果我们使用文本文件,每个都可以正常工作。如果我们使用pdf或jpeg文件,那么它就会在存档中中断,应用程序就不能打开它。
发布于 2022-09-13 10:31:55
您不应该使用readAsBinaryString,而应该使用readAsArrayBuffer (根据这篇关于吉突布的文章,readAsBinaryString将将二进制数据转换为UTF-16字符串,这不是您想要的;通过使用readAsArrayBuffer,您将获得文件的原始字节)。
https://stackoverflow.com/questions/73701270
复制相似问题