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:

| improve this answer | |
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

| improve this answer | |
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;
}
| improve this answer | |
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","");
| improve this answer | |
0
//_spBodyOnLoadFunctionNames.push("AddZipIcon" );
function AddZipIcon() {
// for SP online
$(".ms-qcb-root ul li:nth-child(3)" ).each(function () {
$(this).first().before('<li class=" ms-qcb-item" >' +
'<a class=" ms-qcb-button ms-qcb-buttons-alignmentfix js-listview-qcbUploadButton js-callout-body js-qcb-button ms-qcb-glyph"  type=" button" ' +
'title=" Select files and download as a zip file" accesskey=" z"  onclick=" ConvertToZip()" ><span class=" ms-qcb-glyph ms-listview-glyph-withmargin ms-listview-sync-glyph ms-core-form-heading" ><img style=" height:20px;width:25px;"  src="https://" /></span><span class=" ms-qcb-glyph ">Zip</span></a></li>')
});
}
function CheckDownloadZip()
{
    return true;
}
function ConvertToZip()
{
 var seldocs = GetSelectedItemsDocsURLs();
 if(seldocs != null)
 {
 var dialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Creating Zip with selected files', 'Please wait while the files are added to zip...');

// alert("packaging..");
 DownloadPackage(seldocs);
 dialog.close(0);
 }
 
}
function GetSelectedItemsDocsURLs()
{
var tempurls = [];
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
if (items.length== 0) {
alert("Please select an item from the list" );
return null;
}
else
{
for (var i in items)
{
var getFileName = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists('"  + SP.ListOperation.Selection.getSelectedList()+ "')/items("  + items[i].id + ")/?$select=EncodedAbsUrl" ;
$.ajax({
url: getFileName,
type: "GET" ,
headers: {
"accept" : "application/json;odata=verbose"
},
success: function (listData) {
tempurls.push(listData.d.EncodedAbsUrl);
// filename = fileURL.substr(fileURL.lastIndexOf('/') + 1);
},
error: function (error) {
console.log(JSON.stringify(error))
},
async: false
});

}
}
 return tempurls;
}
function DownloadPackage(urls)
{
var filename = "selecteddocs";
//The function is called
compressed_img(urls, filename);

}
| improve this answer | |

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.