Jszip: Upgrade to jszip 3.1.2

Created on 15 Nov 2016  Â·  4Comments  Â·  Source: Stuk/jszip

I created a function to read a Zip folder and upload in a Document Library Using jszip old version.
Now I want to Upgrade it to jszip 3.1.2

function jspres_importPptxPresentation_handleFileSelect(evt) {
    var $result = $("#result");


    $result.html("");

    // see http://www.html5rocks.com/en/tutorials/file/dndfiles/

    var files = evt.target.files;
    for (var i = 0, f; f = files[i]; i++) {

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                var $title = $("<h3>", {
                    text: theFile.name
                });
                $result.append($title);
                var $ul = $("<ul>");
                try {

                    var dateBefore = new Date();
                    // read the content of the file with JSZip
//-----------------------------------------------------------------------------------------------
                    var zip = new JSZip(e.target.result); //----------------<1>-----
//----------------------------------------------------------------------------------------------
                    var dateAfter = new Date();

                    $title.append($("<span>", {
                        text: " (parsed in " + (dateAfter - dateBefore) + "ms)"
                    }));

                    // that, or a good ol' for(var entryName in zip.files)

                    $.each(zip.files, function (index, zipEntry) {

                        var reader1 = new FileReader();
                        $ul.append("<li>" + zipEntry.name + "</li>");
                        if (!zipEntry.options.dir)

                        {
//--------------------------------------------------------------------------------------------------------- 
                           var addFile = addFileToFolder(zipEntry.asArrayBuffer(), zipEntry.name); //---<2>
//---------------------------------------------------------------------------------------------------
                            addFile.done(function (file, status, xhr) {
                                // Get the list item that corresponds to the uploaded file.
                                var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
                                getItem.done(function (listItem, status, xhr) {
                                    // Change the display name and title of the list item.
                                    var changeItem = updateListItem(listItem.d.__metadata);
                                    changeItem.done(function (data, status, xhr) {
                                        alert('file uploaded and updated');
                                    });
                                    changeItem.fail(onError);
                                });
                                getItem.fail(onError);
                            });
                            addFile.fail(onError);
                        }

                    });
                    // end of the magic !

                } catch (e) {
                    $ul.append("<li class='error'>Error reading " + theFile.name + " : " + e.message + "</li>");
                }
                $result.append($ul);
            }
        })(f);


    }
}

// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer, filename) {
    // Get the file name from the file input control on the page.
    var nameArray = filename.split('/');
    var filenamev = nameArray[nameArray.length - 1];
    //filenamev = filenamev.substring(0, filenamev.indexOf("."));
    var serverRelativeUrlToFolder = 'Shared Documents';
    // Construct the endpoint.
    var fileCollectionEndpoint = String.format(
        "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
        "/add(overwrite=true, url='{2}')?@target='{3}'",
        appWebUrl, serverRelativeUrlToFolder, filenamev, hostWebUrl);

    // Send the request and return the response.
    // This call returns the SharePoint file.
    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "content-length": arrayBuffer.byteLength
        }
    });
}

In Code
<1> Jszip with constructor doesn't accept parameters . Please provide a substitute for it.
<2> asArrayBuffer method is removed from Jszip 3.1.2 . Please provide substitute for it.

questiosupport

Most helpful comment

This code seems to be based on an old examples/read-local-file-api.html. A good start is to check the current version of this code. Then, check the upgrade guide (zipEntry.options.dir is now zipEntry.dir for example).

Your changes start at $.each(zip.files) (which has been replaced by zip.forEach on the current example). From there:

if (!zipEntry.dir) {
  zipEntry.async('arraybuffer').then(function (content) {
    var addFile = addFileToFolder(content, zipEntry.name);
    // ...
  });
}

Note, this code can be simplified if you use jQuery ≥ 3.0 (jQuery.Deferred is now Promises/A+ compatible and can be chained with other promises).

All 4 comments

This code seems to be based on an old examples/read-local-file-api.html. A good start is to check the current version of this code. Then, check the upgrade guide (zipEntry.options.dir is now zipEntry.dir for example).

Your changes start at $.each(zip.files) (which has been replaced by zip.forEach on the current example). From there:

if (!zipEntry.dir) {
  zipEntry.async('arraybuffer').then(function (content) {
    var addFile = addFileToFolder(content, zipEntry.name);
    // ...
  });
}

Note, this code can be simplified if you use jQuery ≥ 3.0 (jQuery.Deferred is now Promises/A+ compatible and can be chained with other promises).

This works for me.
But I face one Issue.
When I User a loop to get List of Files from Zip Folder Using Below Function using Jszip 3.1.2.

zip.forEach(function (relativePath, zipEntry) {
          $fileContent.append($("<li>", {
            text : zipEntry.name
          }));
        });

When I Use This Code I am getting a Path Like this

demo3/demo31 - Copy (2)/
demo3/demo31 - Copy (3)/
demo3/demo31 - Copy/
demo3/demo31/
demo3/demo31/demo31/
demo3/demo31/demo31/demo311 - Copy (2)/
demo3/demo31/demo31/demo311 - Copy (3)/
demo3/demo31/demo31/demo311 - Copy/
demo3/demo31/demo31/demo311/

When I uses older version of jszip I got a Path Like
demo3/
demo3/demo31 - Copy (2)/
demo3/demo31 - Copy (3)/
demo3/demo31 - Copy/
demo3/demo31/
demo3/demo31/demo31/
demo3/demo31/demo31/demo311 - Copy (2)/
demo3/demo31/demo31/demo311 - Copy (3)/
demo3/demo31/demo31/demo311 - Copy/
demo3/demo31/demo31/demo311/

What to do If need Path Like this.
This one is simplest structure but for complicated I faces a problem

That's the createFolders option. When JSZip v3 loads a zip file, it doesn't create all folders, only the ones declared in the zip file. If you want to create all sub folders, change this option:

JSZip.loadAsync(f);
// becomes
JSZip.loadAsync(f, {createFolders: true});

It works.
Thanks it helped me a lot

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghigt picture ghigt  Â·  4Comments

mikeiasNS picture mikeiasNS  Â·  5Comments

RUSHt picture RUSHt  Â·  5Comments

maordany picture maordany  Â·  4Comments

despairblue picture despairblue  Â·  7Comments