SharePoint OnPremises - Client Side File Upload Control And Uploading File In SharePoint Using Rest API

In one of our SharePoint OnPremises projects, we had this requirement to upload the user’s profile image in SharePoint Image library (PublishingImages). So, we implemented this feature using JavaScript and uploaded the image in SharePoint Image library using REST API.

This becomes a generic component and anybody can use this in any SharePoint project. We have used this Control in our couple of Visual WebParts.

In this article, I’ll share step by step details how we implemented and how this component worked.

Environment

SharePoint on premises 2013, didn’t test for SharePoint online but I believe it should work for SharePoint online as well.

Details

We have OOB FileUpload control available in .NET but which causes page postback so we decided to implement client-side control.

Step 1

Use <input> element with type “file”. This lets the user select one or more files. File input renders the button “Choose File”. On click of this button, file picker dialog opens with a label which shows the file name.

  1. <input type="file" draggable="true" id="fileupload" class="form-control" />  

File Input element
Figure 1: File Input element

On click of “Choose File” button, "file open" dialog box opens and we can select one or multiple files from it. Here, in this case, we require only one file and so only one file will be selected at a time. 

File Input element
Figure 2: Open file dialog box, opens when "Choose File" button is clicked

Step 2

We have added one more button “Upload Profile”. On click of this button, we are uploading image in SharePoint Images library.

 "Upload Profile" button with File Input control
Figure 3: "Upload Profile" button with File Input control

Step 3

On “Upload Profile” button click, we will upload the selected file using REST APIs. We are calling JavaScript method “UploadFile”.

  1. <input type="button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" />  

Here also, it is showing OOB wait dialog box till the image gets uploaded in SharePoint.

Following are the detailed steps to upload file using rest API from JavaScript

  1. Get the file element.
    1. var fileElement = <%=fileupload.ClientID%>;  
  1. Check if file is selected or not, if not then showing alert message.
    1. if (fileElement.files.length === 0) {  
    2.             alert('No file was selected');  
    3.             return;  
    4.         }//if (fileElement.files.length === 0)  
  1. Since we are using REST API call back happens, we are showing OOB SharePoint wait dialog box till the file is get uploaded in SharePoint Images library.
    1. var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Profile Image upload in progress"'', 80, 560);  
  1. Get the file name.
    1. var parts = fileElement.value.split("\\");  
    2. var filename = parts[parts.length - 1];  
  1. Read the file and once done, call the REST API. We are using FileReader object which lets us asynchronously read the content of file. There is a FileReader.readyState property having possible values of the state are,

     EMPTY 0 No data is loaded yet
     LOADING 1 Data is currently being loading
     DONE 2 Read request is done
    1. var fileReader = new FileReader();  
    2. //File loaded  
    3. fileReader.onloadend = function (event) {  
    4.            if (event.target.readyState == FileReader.DONE) {  
    5.               var filecontent = event.target.result;  
    6.           
    7. //Code to upload image in Images Library   
    8.       }  
  1. Upload the image to Images library using REST APIs.
    1.  //SharePoint images library path  
    2.         var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl +   
    3.           "PublishingImages";  
    4.                 
    5.         //Complete REST API  
    6.  var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl  
    7.               + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL +   
    8. "')/Files/add(url='" + filename + "',overwrite=true)";  
    9.   
    10.                  
    11. $.ajax({  
    12.                url: completeImageLibraryUrl,  
    13.                type: "POST",  
    14.                data: filecontent,  
    15.                async: false,  
    16.                processData: false,  
    17.                headers: {  
    18.                 "accept""application/json;odata=verbose",  
    19.                       "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
    20.                },  
    21.                complete: function (data) {  
    22.                var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);  
    23.                         var web = clientContext.get_web();  
    24.                         var fileurl = imagelibraryURL + "/"+filename;  
    25.                         var imagetopublish = web.getFileByServerRelativeUrl(fileurl);  
    26.   
    27.                         imagetopublish.checkIn();  
    28.                         imagetopublish.publish();  
    29.                         clientContext.executeQueryAsync();  
    30.                 //close the wait dialog  
    31.                         if (waitDialog_FileUpload != null) {  
    32.                             waitDialog_FileUpload.close();  
    33.                         }  
    34.                         alert("Your profile image uploaded successfully");  
    35.                      }, //complete  
    36.                      error: function (err) {  
    37.                           if (waitDialog_FileUpload != null) {  
    38.                               waitDialog_FileUpload.close();  
    39.                            }  
    40.                            alert(err + err.message + err.stacktrace);  
    41.                      }//error  
    42.                 });//$.ajax  
    43.   
    44.             fileReader.readAsArrayBuffer(fileElement.files[0]);  

Complete Code

HTML

  1. <input type="file" draggable="true" id="fileupload" class="form-control" />  
  2. <input type="button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" />  
JS
  1. function UploadFile() {  
  2.         var fileElement = <%=fileupload.ClientID%>;  
  3.         if (fileElement.files.length === 0) {  
  4.             alert('No file was selected');  
  5.             return;  
  6. }//if (fileElement.files.length === 0)  
  7.        else {  
  8. var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Profile Image upload in progress"'', 80, 560);  
  9. var parts = fileElement.value.split("\\");  
  10.        var filename = parts[parts.length - 1];  
  11. var fileReader = new FileReader();  
  12. //File loaded  
  13. fileReader.onloadend = function (event) {  
  14.            if (event.target.readyState == FileReader.DONE) {  
  15.               var filecontent = event.target.result;  
  16.           
  17. //Code to upload image in Images Library  
  18. var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl +   
  19.           "PublishingImages";  
  20.                 
  21.         //Complete REST API  
  22.  var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl  
  23.               + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL +   
  24. "')/Files/add(url='" + filename + "',overwrite=true)";  
  25.   
  26.                  
  27. $.ajax({  
  28.                url: completeImageLibraryUrl,  
  29.                type: "POST",  
  30.                data: filecontent,  
  31.                async: false,  
  32.                processData: false,  
  33.                headers: {  
  34.                 "accept""application/json;odata=verbose",  
  35.                       "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  36.                },  
  37.                complete: function (data) {  
  38.                var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);  
  39.                         var web = clientContext.get_web();  
  40.                         var fileurl = imagelibraryURL + "/"+filename;  
  41.                         var imagetopublish = web.getFileByServerRelativeUrl(fileurl);  
  42.   
  43.                         imagetopublish.checkIn();  
  44.                         imagetopublish.publish();  
  45.                         clientContext.executeQueryAsync();  
  46.                 //close the wait dialog  
  47.                         if (waitDialog_FileUpload != null) {  
  48.                             waitDialog_FileUpload.close();  
  49.                         }  
  50.                         alert("Your profile image uploaded successfully");  
  51.                      }, //complete  
  52.                      error: function (err) {  
  53.                           if (waitDialog_FileUpload != null) {  
  54.                               waitDialog_FileUpload.close();  
  55.                            }  
  56.                            alert(err + err.message + err.stacktrace);  
  57.                      }//error  
  58. });//$.ajax  
  59.     }// if (event.target.readyState == FileReader.DONE)  
  60.             fileReader.readAsArrayBuffer(fileElement.files[0]);  
  61.           
  62.   }//else  
  63. }//UploadFile      

References

  1. <input type="file">
  2. FileReader object
  3. Rest API to upload the file
  4. OOB SharePoint Wait dialog box

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now