Upload Files To Document Library Using SharePoint REST API

Hi there, hope everyone is safe!
 
In this blog, you will learn about uploading documents to the SharePoint Document library using JavaScript REST API.
 
Let's get started,
 
Prerequisites
  1. Create a Document Library
  2. A Site Page
  3. Upload code to site assets from my Github

What is a Document Library?

  1. Add, edit, delete a file, folder, or link from a SharePoint document library, co-author, and download documents.
  2. Control who has access to a library, a folder within a library, or a private file within a library.
  3. Track the activity on a file, like when it had been last modified, and receive a notification when something has changed.
  4. Share files or folders with others.
  5. Add a link in a document library to something that is stored outside the library, for example, a link to a file located in a different library or even a link to an external web page.
  6. Highlight a link, file, or folder during a document library so you can get to them quickly.

Upload any File to Document Library using REST API in just 3 simple steps

 
STEP 1
 
Specify the type of a file in HTML, here I have specified DOCX and PDF
  1. <div style="margin-top: 10%;">  
  2.    <input id = "attachment" type = "file" multiple accept = ".DOCX,.docx,.txt,.TXT,.PDF,.pdf" />  
  3.    <br/>  
  4.    <div>  
  5.        <button  id = "addFileButton" type = "button" class="btn btn-primary" onclick = "uploadDocument()">Upload</button>  
  6.    </div>  
  7.  </div>  
STEP 2
 
After selecting the file from the popup window, click on the upload button and uploadDocument() function gets triggered.  
 
Without selecting a file when user click's on the button warning alert displays,
  1. function uploadDocument() {  
  2.     var files = $("#attachment")[0].files;  
  3.     if (files.length > 0) {  
  4.         fileName = files[0].name;  
  5.         var webUrl = _spPageContextInfo.webAbsoluteUrl;  
  6.         var documentLibrary = "DemoLibrary";  
  7.         var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;  
  8.         // Construct the Endpoint  
  9.         var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(@target)/Files/add(overwrite=true, url='" + fileName + "')?@target='" + targetUrl + "'&$expand=ListItemAllFields";  
  10.         uploadFileToFolder(files[0], url, function(data) {  
  11.             var file = data.d;  
  12.             DocFileName = file.Name;  
  13.             var updateObject = {  
  14.                 __metadata: {  
  15.                     type: file.ListItemAllFields.__metadata.type  
  16.                 },  
  17.                 FileLeafRef: DocFileName //FileLeafRef --> Internal Name for Name Column  
  18.             };
  19.             alert("File uploaded successfully!");  
  20.         }, function(data) {  
  21.             alert("File uploading failed");  
  22.         });  
  23.     } else {  
  24.         alert("Kindly select a file to upload.!"); 
  25.     }  
  26. }  
STEP 3
  1. // Get the local file as an array buffer.  
  2. function getFileBuffer(uploadFile) {  
  3.     var deferred = jQuery.Deferred();  
  4.     var reader = new FileReader();  
  5.     reader.onloadend = function(e) {  
  6.         deferred.resolve(e.target.result);  
  7.     }  
  8.     reader.onerror = function(e) {  
  9.         deferred.reject(e.target.error);  
  10.     }  
  11.     reader.readAsArrayBuffer(uploadFile);  
  12.     return deferred.promise();  
  13. }  
File gets uploaded using array buffer (local file Meta Data) and POST method to upload to document folder, 
  1. function uploadFileToFolder(fileObj, url, success, failure) {  
  2.     var apiUrl = url;  
  3.     // Initiate method calls using jQuery promises.  
  4.     // Get the local file as an array buffer.  
  5.     var getFile = getFileBuffer(fileObj);  
  6.     // Add the file to the SharePoint folder.  
  7.     getFile.done(function(arrayBuffer) {  
  8.         $.ajax({  
  9.             url: apiUrl,//File Collection Endpoint  
  10.             type: "POST",  
  11.             data: arrayBuffer,  
  12.             processData: false,  
  13.             async: false,  
  14.             headers: {  
  15.                 "accept""application/json;odata=verbose",  
  16.                 "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),  
  17.             },  
  18.             success: function(data) {  
  19.                 success(data);  
  20.             },  
  21.             error: function(data) {  
  22.                 success(data);  
  23.             }  
  24.         });  
  25.     });  
  26. }  
Screenshots
 
 Upload Files To Document Library Using SharePoint REST API
 Figure 1
 
Upload Files To Document Library Using SharePoint REST API
Figure 2
 
Upload Files To Document Library Using SharePoint REST API
Figure 3 
 
Upload Files To Document Library Using SharePoint REST API
Figure 4 
 
Hurray!! We have successfully uploaded the file to the document library.
 
To know more you can refer to the official documentation,
HexaCorp
Expertise in the cloud, speed of innovation and customer focus on building strong relationships