Upload Multiple Files To SharePoint List On Single Click Using Angular And jQuery

Introduction

This article explains how to upload multiple files into a SharePoint list in just a single click using Angular and jQuery.

Objective

Post multiple files into a SharePoint list in just one click.

Procedure

  • Create a SharePoint library for storing files

    SharePoint
  • Create a web page for UI to upload files.

    SharePoint
  • Build respective HTML and script for the web page.

HTML Code

  1. <label class="btn btn-warning btn-xs" style="background-color: #6E2143;color: beige;" meetid="getFile" onclick="angular.element(this).scope().btnAgUpload(this)">  
  2. <span class="glyphicon glyphicon-open"></span>Upload</label>  
  3. <input type="file" id="getFile" multiple="multiple" onchange="angular.element(this).scope().uploadfiles(this)" style="display:none" />  

Here we are hiding the input with style tag (display:none), but when we click on label, it triggers to the hidden input by onchange.

When onchange starts the trigger, it will call the actual upload function as shown in the script code.

Script Code

Label click

  1. $scope.btnAgUpload = function(val1){  
  2.      var fileEle = val1.attributes['meetid'].value;       
  3.      document.getElementById(fileEle).click();  
  4.      }  

Hidden input calls the upload function.

  1. $scope.uploadfiles = function (ele){  
  2.         var agendaFile = $("#"+ele.attributes['id'].value);   
  3.         upload(agendaFile)  
  4.         }  

Explanation for Upload functionality.

  1. function upload(sm) {/* passing the selected files as objects*/  
  2.     var serverRelativeUrlToFolder = 'TestForMultipleFiles';    /*Define the folder path for this example.*/  
  3.   
  4.     var fileInput = sm;    /* Get test values from the file input and text input page controls.*/  
  5.     var fileCount = fileInput[0].files.length;  
  6.     var serverUrl = _spPageContextInfo.webAbsoluteUrl;    /*Get the server URL.*/  
  7.     var filesUploaded = 0;  
  8.     for(var i = 0; i < fileCount; i++){  
  9.         /* Initiate method calls using jQuery promises. Get the local file as an array buffer.*/  
  10.         var getFile = getFileBuffer(i);  
  11.         getFile.done(function (arrayBuffer,i) {  
  12.             /*Add the file to the SharePoint folder.*/  
  13.             var addFile = addFileToFolder(arrayBuffer,i);  
  14.             addFile.done(function (file, status, xhr) {  
  15.                 filesUploaded++;  
  16.                 if(fileCount == filesUploaded){  
  17.                         $("#getFile").val('');/* resetting the input*/  
  18.                     alert("All files uploaded successfully");/* success alert*/  
  19.                     filesUploaded = 0;  
  20.                 }  
  21.             });  
  22.             addFile.fail(onError);  
  23.         });  
  24.         getFile.fail(onError);  
  25.   
  26.     }  
  27.   
  28.     /* Get the local file as an array buffer.*/  
  29.     function getFileBuffer(i) {  
  30.         var deferred = jQuery.Deferred();  
  31.         var reader = new FileReader();  
  32.         reader.onloadend = function (e) {  
  33.             deferred.resolve(e.target.result,i);  
  34.         }  
  35.         reader.onerror = function (e) {  
  36.             deferred.reject(e.target.error);  
  37.         }  
  38.         reader.readAsArrayBuffer(fileInput[0].files[i]);  
  39.         return deferred.promise();  
  40.     }  
  41.   
  42.     /* Add the file to the file collection in the Shared Documents folder.*/  
  43.     function addFileToFolder(arrayBuffer,i) {  
  44.     var index = i;  
  45.   
  46.         /* Get the file name from the file input control on the page.*/  
  47.         var fileName = fileInput[0].files[index].name;  
  48.         var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds  
  49.     var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0,-1).replace(":""").slice(0,-2).replace(":""").slice(0,-3).replace(".""");  
  50.         CustomFilename = fileName.replace(".docx"""+localISOTime+".docx");/* customizing the file name*/  
  51.         /* Construct the endpoint.*/  
  52.         var fileCollectionEndpoint = String.format(  
  53.                 "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +  
  54.                 "/add(overwrite=true, url='{2}')",  
  55.                 serverUrl, serverRelativeUrlToFolder, CustomFilename);  
  56.   
  57.         /* Send the request and return the response. 
  58.         This call returns the SharePoint file.*/  
  59.         return jQuery.ajax({  
  60.             url: fileCollectionEndpoint,  
  61.             type: "POST",  
  62.             data: arrayBuffer,  
  63.             processData: false,  
  64.             headers: {  
  65.                 "accept""application/json;odata=verbose",  
  66.                 "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()  
  67.             }  
  68.         });  
  69.     }  
  70. }  
  71.   
  72. /* Display error messages. */  
  73. function onError(error) {  
  74.     alert(error.responseText);  
  75. }  

Let’s see the result on the screen as below.

Click on "Upload" and select multiple files.

SharePoint

Then, click on "Open". We get the success alert.

SharePoint

Go back to your list and check.

SharePoint
Finally, the selected files are uploaded successfully into SharePoint list.

Conclusion

Hope this will be the smart way to upload multiple files in just one click to SharePoint list using Angular and jQuery. And, avoid too many clicks to upload files.

Up Next
    Ebook Download
    View all
    Learn
    View all