1

How do I zip and download all the files (keeping the folder structure) from a document library using Jsom and jzip Library?

Download multiple files then compress to one zip file using JSZip & JSZip-utils generate a single zip with multiple files with in multiple folder.from the code below I am able generate each zip for each folder with in a document library i want a single zip for all the folders

6

You could consider the following solution:

Example

loadFiles("Documents/2013",
        function(files) {
           var zip = new JSZip(); 
           zipFiles(zip,files,0,function(content){
               console.log('Done.');
               saveAs(content, "archive.zip"); 
           });
        },
        function(sender,args){
            console.log(args.get_message());
        }
    );

where

function zipFiles(zip,files,index,complete){
    index = index || 0;
    var curFile = files.get_item(index);
    JSZipUtils.getBinaryContent(curFile.get_serverRelativeUrl(), function (err, data) {
       if(err) {
           throw err; // or handle the error
       }
       zip.file(curFile.get_name(), data, {binary:true}); 
       index++;
       if(index < files.get_count()) {
         zipFiles(zip,files,index,complete);
       }  
       else {
         zip.generateAsync({type:"blob"})
         .then(function(content) {
              complete(content);
         });  
       }       
    });
}


function loadFiles(folderUrl,success,error){
   var ctx = SP.ClientContext.get_current();
   var web = ctx.get_web();
   var folder = web.getFolderByServerRelativeUrl(folderUrl);
   var files = folder.get_files();
   ctx.load(files);
   ctx.executeQueryAsync(
        function() {
           success(files);          
        },
        error); 
}

dependencies:

0

It isn't clear what version you are using from your question. Microsoft just announced this feature is coming with the modern SharePoint libraries in Office 365.

https://support.office.com/en-us/article/Download-OneDrive-files-and-folders-5c7397b7-19c7-4893-84fe-d02e8fa5df05?ui=en-US&rs=en-US&ad=US&fromAR=1

0

download all the files (keeping the folder structure) from a document library

function Zip()
{
    deferreds = [];
    Fileurl=""; 
    filename="";
    array_Names=["abc","efg"];

    var Documentscxt = new SP.ClientContext.get_current();
    this.docs = Documentscxt.get_web().get_lists().getByTitle("Documents");
    var query = SP.CamlQuery.createAllItemsQuery();
    DocumentsallItems  = docs.getItems(query);
    Documentscxt .load(docs);
    Documentscxt .load(DocumentsallItems, 'Include(Title, ContentType,File,ID)');
    Documentscxt .executeQueryAsync(ZipDocument, onQueryFailed);                                                        
}

function ZipDocument()
{   
    var fileUrls="";
     var ListEnumerator = DocumentsallItems.getEnumerator();
        while (ListEnumerator.moveNext()) {
            var currentItem = ListEnumerator.get_current();
            var _contentType = currentItem.get_contentType();
            for(var i=1;i<array_Names.length;i++)
            { 
          if (_contentType.get_name() != "Folder") {

                var File = currentItem.get_file();

                  if (File != null) {

                   fileUrls += File.get_serverRelativeUrl() + '\n';
                   var url = fileUrls.split('/');
                   var folder = url[url.length - 2];   
                   if (folder == array_Names[i]) {
                   Fileurl = _spPageContextInfo.siteAbsoluteUrl+'/sites/Documents/'+array_Names[i]+'/'+File.get_name();
                   filename=File.get_name();
                   var getFilesFromFolder =_spPageContextInfo.siteAbsoluteUrl+'/sites/Documents/'+array_Names[i];

                        $.ajax({
                        url: getFilesFromFolder,
                        type: "GET",
                        headers: {
                            "accept": "application/json;odata=verbose"
                        },
                        success: function () {
                            deferreds.push(deferredAddZip(Fileurl,filename, zip, 1, array_Names[i]));
                        },

                        error: function (error) 
                        {
                            console.log(JSON.stringify(error))
                        },

                        async: false
                    });
                   } 


                }   
            }
        }     
    }
    $.when.apply($, deferreds).done(function () {
                zip.generateAsync({type:"blob"}).then(function(content) {
                saveAs(content, "Document.zip");
                });
            });
}               
function deferredAddZip(url, filename, zip, isFolder, folderName) 
{
    var deferred = $.Deferred(); //for synchronous calls
    JSZipUtils.getBinaryContent(url, function (err, data) {
        if (err) {
            deferred.reject(err);
            } else {
            if (isFolder != 1) {
                zip.file(filename, data, {
                    binary: true
                });
                } else {
                zip.folder(folderName).file(filename, data, {
                    binary: true
                });
            }
            deferred.resolve(data);
        }
    });

    return deferred;
}
0

I put this together that will let you zip an array of image urls.

https://jsfiddle.net/jaitsujin/zrdgsjht/

You can manage zip folder structure by modifying this line

filename = filename.replace(/[\/\*\|\:\<\>\?\"\\]/gi, '').replace("httpsi.imgur.com","");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.