Turtle corporation
Turtle corporation

Reputation: 76

How to zip an img from file input with JSZIP

I try to zip a file from a file input element, but it does not work. How can I do it by using Javascript?

var input = document.getElementById("id1");
const filereader = new FileReader();
filereader.onload = function() {
  zip.file("picture.png", filereader.result, {binary: true});
}
filereader.readAsDataURL(input.files[0]);
<input type="file" id="id1" style="border-radius: 0.1px; width: 40%;" accept="image/*">

Upvotes: 1

Views: 1367

Answers (1)

Doan Van Thang
Doan Van Thang

Reputation: 997

As zip.file(name, data [,options]) accept blob datatype, you just need to get it's files

    document.getElementById("id1").addEventListener("change", function (params) {
        var zip = new JSZip();
        var temp = this.files[0];
        zip.file(temp.name, temp);
        zip.generateAsync({ type: "blob" })
            .then(function (content) {
                // see FileSaver.js
                saveAs(content, "example.zip");
            });
    })

Upvotes: 2

Related Questions