user3378165 user3378165 - 1 month ago 7
Javascript Question

Zip and Download multiples PDF documents with javascript

On my Javascript code, I have a mapped array of documents locations (with Knockout).

var mappedArray = $.map(self.checkedDocs(), function (item) { return item.pdfloc() });


Is that possible to Zip and Download these documents using Javascript?

Answer

I ended up zipping the documents on the server and once they are zipped I download them in client side:

self.download = function () {
    var mappedArray = $.map(self.checkedDocs(), function (item) { return item.pdfloc() });
    self.service.zipDocs(ko.toJSON(mappedArray), function (data) {
        if (data == "Error") {
            $("#modalResult").text("Error has occured, please try later.");
            $("#modalConfirmation").dialog();
        }
        else if (data == "Success") {
            $("#modalResult").text("Your documents are being download.");
            $("#modalConfirmation").dialog();
        }
    });
}

And the API call:

self.zipDocs = function (docs, callback) {
    $.ajax({
        url: "http://api.xxx.com/functions/zip",
        type: "POST",
        contentType: "application/json",
        dataType: "binary",
        data: docs,
        processData: false,
        success: function (blob) {
            saveAs(blob, "ZippedDocuments.zip");
            callback("Success");
        },
        error: function (data) {
            callback("Error");
        }
    });
}

And the API c# cofr:

[HttpPost]
[Route("zip")]
public HttpResponseMessage ZipDocs([FromBody] string[] docs)
{
    using (ZipFile zip = new ZipFile())
    {
        zip.AddFiles(docs, false, "");
        return ZipContentResult(zip);
    }
}

I hope it will help to those who are facing the same issue.

Comments