Search code examples
javascriptjszip

JSZip corrupts pdf and jpeg files


Here is a very simple example of zipping file with JSZip (codepen example)

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)
}

If we use text file, everythig works fine. If we use a pdf or jpeg file, then it breaks in the archive and cannot be opened by applications


Solution

  • You shouldn't use readAsBinaryString, use readAsArrayBuffer instead (according to this post on Github, readAsBinaryString will convert the binary data to a UTF-16 string, which isn't what you want; by using readAsArrayBuffer, you'll get the raw bytes of the file).