SharePoint OnPremises: Client side file upload control and uploading file in SharePoint using rest API

Figure 1: SharePoint OnPremises - File Input element
Figure 1: SharePoint OnPremises - File Input element

Hi All,

Today new discussion, which we implemented in our one of the SharePoint 2013 project.

Background: In one of our SharePoint OnPremises project, we have requirement to upload the user’s photo, his profile image in SharePoint Image library (PublishingImages). So we have implemented this feature using JavaScript and upload image in SharePoint Image library using rest API.

This become 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 works.

Environment: SharePoint on premises 2013, didn’t tested 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 post back so we decided to implement client side control.

Step 1: Using <input> element with type “file”. This let the user to select one or more files. File input renders the button “Choose File”, on click of this button file picker dialog opens and label which shows the file name as

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

Figure 1: SharePoint OnPremises – File Input element

On click of “Choose File” button file open dialog box opens as and we can select the one or multiple files from it. Here in case we required only one file and so considering each time that only one file will be selected at a time.

Figure 2: SharePoint OnPremises – 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 as

Figure 3: SharePoint OnPremises – “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” as

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

Here also showing OOB wait dialog box till the image get uploaded in SharePoint.
Following are the detailed steps to upload file using rest API from JavaScript

1. Get the file element as
var fileElement = <%=fileupload.ClientID%>;

2. Check if file is selected or not, if not then showing alert message as

if (fileElement.files.length === 0) {
            alert('No file was selected');
            return;
        }//if (fileElement.files.length === 0)

3. 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 as

var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Profile Image upload in progress", '', 80, 560);

4. Get the file name as
var parts = fileElement.value.split("\\");
       var filename = parts[parts.length - 1];

5. Read the file and once done call the rest api as, we are using FileReader object which let 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

var fileReader = new FileReader();
//File loaded
fileReader.onloadend = function (event) {
           if (event.target.readyState == FileReader.DONE) {
              var filecontent = event.target.result;
            
//Code to upload image in Images Library
         }

6. Uploading image to Images library using REST APIs
      
 //SharePoint images library path
       var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl +
          "PublishingImages";
             
        //Complete REST API
 var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl
     + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL +
"')/Files/add(url='" + filename + "',overwrite=true)";
              
$.ajax({
               url: completeImageLibraryUrl,
               type: "POST",
               data: filecontent,
               async: false,
               processData: false,
               headers: {
                    "accept": "application/json;odata=verbose",
                      "X-RequestDigest": $("#__REQUESTDIGEST").val(),
               },
               complete: function (data) {
                       var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);

      var web = clientContext.get_web();
      var fileurl = imagelibraryURL + "/"+filename;
      var imagetopublish = web.getFileByServerRelativeUrl(fileurl);

                        imagetopublish.checkIn();
                        imagetopublish.publish();
                        clientContext.executeQueryAsync();
                        //close the wait dialog
                        if (waitDialog_FileUpload != null) {
                            waitDialog_FileUpload.close();
                        }
                     alert("Your profile image uploaded successfully");
                     }, //complete
                     error: function (err) {
                          if (waitDialog_FileUpload != null) {
                              waitDialog_FileUpload.close();
                           }
                           alert(err + err.message + err.stacktrace);
                     }//error
                });//$.ajax

            fileReader.readAsArrayBuffer(fileElement.files[0]);
Complete Code:

HTML:

<input type="file" draggable="true" id="fileupload" class="form-control" />
<input type="button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" />

JavaScript:

function UploadFile() {
        var fileElement = <%=fileupload.ClientID%>;
        if (fileElement.files.length === 0) {
            alert('No file was selected');
            return;
}//if (fileElement.files.length === 0)
       else {
var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Profile Image upload in progress", '', 80, 560);
var parts = fileElement.value.split("\\");
       var filename = parts[parts.length - 1];
var fileReader = new FileReader();
//File loaded
fileReader.onloadend = function (event) {
           if (event.target.readyState == FileReader.DONE) {
              var filecontent = event.target.result;
            
//Code to upload image in Images Library
var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl +
          "PublishingImages";
             
        //Complete REST API
 var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl
              + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL +
"')/Files/add(url='" + filename + "',overwrite=true)";

              
$.ajax({
               url: completeImageLibraryUrl,
               type: "POST",
               data: filecontent,
               async: false,
               processData: false,
               headers: {
                    "accept": "application/json;odata=verbose",
                      "X-RequestDigest": $("#__REQUESTDIGEST").val(),
               },
               complete: function (data) {
                       var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
                        var web = clientContext.get_web();
                        var fileurl = imagelibraryURL + "/"+filename;
                        var imagetopublish = web.getFileByServerRelativeUrl(fileurl);

                        imagetopublish.checkIn();
                        imagetopublish.publish();
                        clientContext.executeQueryAsync();
                        //close the wait dialog
                        if (waitDialog_FileUpload != null) {
                            waitDialog_FileUpload.close();
                        }
                        alert("Your profile image uploaded successfully");
                     }, //complete
                     error: function (err) {
                          if (waitDialog_FileUpload != null) {
                              waitDialog_FileUpload.close();
                           }
                           alert(err + err.message + err.stacktrace);
                     }//error
});//$.ajax
       }// if (event.target.readyState == FileReader.DONE)
            fileReader.readAsArrayBuffer(fileElement.files[0]);
            
  }//else
}//UploadFile

References:

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

Thanks for reading  🙂

Keep reading, share your thoughts, experiences. Feel free to contact us to discuss more. If you have any suggestion / feedback / doubt, you are most welcome.

Stay tuned on Knowledge-Junction, will come up with more such articles

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Microsoft 365

Subscribe now to keep reading and get access to the full archive.

Continue reading