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
- Create a Document Library
- A Site Page
- Upload code to site assets from my Github.
What is a Document Library?
- Add, edit, delete a file, folder, or link from a SharePoint document library, co-author, and download documents.
- Control who has access to a library, a folder within a library, or a private file within a library.
- Track the activity on a file, like when it had been last modified, and receive a notification when something has changed.
- Share files or folders with others.
- 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.
- 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
- <div style="margin-top: 10%;">
- <input id = "attachment" type = "file" multiple accept = ".DOCX,.docx,.txt,.TXT,.PDF,.pdf" />
- <br/>
- <div>
- <button id = "addFileButton" type = "button" class="btn btn-primary" onclick = "uploadDocument()">Upload</button>
- </div>
- </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,
- function uploadDocument() {
- var files = $("#attachment")[0].files;
- if (files.length > 0) {
- fileName = files[0].name;
- var webUrl = _spPageContextInfo.webAbsoluteUrl;
- var documentLibrary = "DemoLibrary";
- var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
-
- var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(@target)/Files/add(overwrite=true, url='" + fileName + "')?@target='" + targetUrl + "'&$expand=ListItemAllFields";
- uploadFileToFolder(files[0], url, function(data) {
- var file = data.d;
- DocFileName = file.Name;
- var updateObject = {
- __metadata: {
- type: file.ListItemAllFields.__metadata.type
- },
- FileLeafRef: DocFileName
- };
- alert("File uploaded successfully!");
- }, function(data) {
- alert("File uploading failed");
- });
- } else {
- alert("Kindly select a file to upload.!");
- }
- }
STEP 3
-
- function getFileBuffer(uploadFile) {
- var deferred = jQuery.Deferred();
- var reader = new FileReader();
- reader.onloadend = function(e) {
- deferred.resolve(e.target.result);
- }
- reader.onerror = function(e) {
- deferred.reject(e.target.error);
- }
- reader.readAsArrayBuffer(uploadFile);
- return deferred.promise();
- }
File gets uploaded using array buffer (local file Meta Data) and POST method to upload to document folder,
- function uploadFileToFolder(fileObj, url, success, failure) {
- var apiUrl = url;
-
-
- var getFile = getFileBuffer(fileObj);
-
- getFile.done(function(arrayBuffer) {
- $.ajax({
- url: apiUrl,
- type: "POST",
- data: arrayBuffer,
- processData: false,
- async: false,
- headers: {
- "accept": "application/json;odata=verbose",
- "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
- },
- success: function(data) {
- success(data);
- },
- error: function(data) {
- success(data);
- }
- });
- });
- }
Screenshots
Figure 1
Figure 2
Figure 3
Figure 4
Hurray!! We have successfully uploaded the file to the document library.
To know more you can refer to the official documentation,