Upload File To Document Library In SharePoint 2016 JavaScript Object Model

Document library acts as the primary repository for the document collaboration in SharePoint. It provides the flexibility to version documents, check-out/check-in, implement retention policies and performs other collaboration options. We can upload the documents to the document library easily. However, we will be faced with the requirement to programmatically upload the documents into the SharePoint library as well. We get the dialog, as shown below, which can be used to browse and upload the documents.



Let’s see how we can implement the file upload to the document library, using the JavaScript object model. In order to provide browsing and selection of the documents,  we will be using HTML 5 input control. Make sure you are using IE version greater than 8, else HTML 5 support won’t be available.

  • Add reference to jQuery file.
    1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    2. <script language="javascript" type="text/javascript">  
  • Within a document, call SP.SOD.executeFunc, so as to load script SP.js. Since we are trying to upload a file from the local machine, we will use HTML 5 input control to read the file contents and upload it as an attachment.

    Call the main starting point function, say registerClick.
    1. SP.SOD.executeFunc('sp.js''SP.ClientContext', registerClick);  
  • Instantiate FileReader object and read the contents of the local file.
    1. varreader = new FileReader();  
    2. reader.onload = function(e)  
    3. {  
    4.     uploadFile(e.target.result, fileName);  
    5. }  
    6. reader.onerror = function(e)  
    7. {  
    8.     alert(e.target.error);  
    9. }  
    10. reader.readAsArrayBuffer(file);  
  • Instantiate the client context and get the list instance.
    1. varclientContext= new SP.ClientContext();  
    2. varoWeb= clientContext.get_web();  
    3. varoList= oWeb.get_lists().getByTitle('Documents');  
  • Convert the file contents into base64 data.
    1. varbytes = new Uint8Array(arrayBuffer);  
    2. vari, length, out = '';  
    3. for (i = 0, length = bytes.length; i < length; i += 1)  
    4. {  
    5.     out += String.fromCharCode(bytes[i]);  
    6. }  
    7. varbase64 = btoa(out);  
  • Create FileCreationInformation object, using the read file data and add the document to the library.
    1. varcreateInfo= new SP.FileCreationInformation();  
    2. createInfo.set_content(base64);  
    3. createInfo.set_url(fileName);  
    4.   
    5. //Add the file to the library  
    6. varuploadedDocument= oList.get_rootFolder().get_files().add(createInfo)  
  • Load the client context and execute the batch which will send the request to the Server and perform the entire JavaScript object model operations as a batch.
    1. clientContext.load(uploadedDocument);  
    2. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
    Full Code:
    1. <html>  
    2.   
    3. <head>  
    4.   
    5.     <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    6.     <script language="javascript" type="text/javascript">  
    7.         varfileInput;  
    8.         $(document).ready(function()  
    9.         {  
    10.             fileInput = $("#getFile");  
    11.             SP.SOD.executeFunc('sp.js''SP.ClientContext', registerClick);  
    12.         });  
    13.   
    14.         function registerClick()  
    15.         {  
    16.             //Register File Upload Click Event  
    17.             $("#addFileButton").click(readFile);  
    18.         }  
    19.         vararrayBuffer;  
    20.   
    21.         function readFile()  
    22.         {  
    23.             //Get File Input Control and read th file name  
    24.             varelement = document.getElementById("getFile");  
    25.             varfile = element.files[0];  
    26.             varparts = element.value.split("\\");  
    27.             varfileName = parts[parts.length - 1];  
    28.             //Read File contents using file reader  
    29.             varreader = new FileReader();  
    30.             reader.onload = function(e)  
    31.             {  
    32.                 uploadFile(e.target.result, fileName);  
    33.             }  
    34.             reader.onerror = function(e)  
    35.             {  
    36.                 alert(e.target.error);  
    37.             }  
    38.             reader.readAsArrayBuffer(file);  
    39.         }  
    40.         varattachmentFiles;  
    41.   
    42.         function uploadFile(arrayBuffer, fileName)  
    43.         {  
    44.             //Get Client Context,Web and List object.  
    45.             varclientContext = new SP.ClientContext();  
    46.             varoWeb = clientContext.get_web();  
    47.             varoList = oWeb.get_lists().getByTitle('Documents');  
    48.             //Convert the file contents into base64 data  
    49.             varbytes = new Uint8Array(arrayBuffer);  
    50.             vari, length, out = '';  
    51.             for (i = 0, length = bytes.length; i < length; i += 1)  
    52.             {  
    53.                 out += String.fromCharCode(bytes[i]);  
    54.             }  
    55.             varbase64 = btoa(out);  
    56.             //Create FileCreationInformation object using the read file data  
    57.             varcreateInfo = new SP.FileCreationInformation();  
    58.             createInfo.set_content(base64);  
    59.             createInfo.set_url(fileName);  
    60.             //Add the file to the library  
    61.             varuploadedDocument = oList.get_rootFolder().get_files().add(createInfo)  
    62.             //Load client context and execcute the batch  
    63.             clientContext.load(uploadedDocument);  
    64.             clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
    65.         }  
    66.   
    67.         function QuerySuccess()  
    68.         {  
    69.             console.log('File Uploaded Successfully.');  
    70.         }  
    71.   
    72.         function QueryFailure(sender, args)  
    73.         {  
    74.             console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
    75.         }  
    76.     </script>  
    77. </head>  
    78.   
    79. <body>  
    80.     <input id="getFile" type="file" /><br />  
    81.     <input id="addFileButton" type="button" value="Upload" />  
    82. </body>  
    83. <html>  

We can test this in SharePoint, by adding it to the content editor Web part, as shown below:

  • Save the code, depicted above, to a text file and save it into one of the SharePoint Libraries, say Site Assets.

  • Go to the edit settings of the SharePoint page and click Web part from the Insert tab.



  • Add content editor Web part.



  • Click on edit Web art from content edit Web part. Assign the URL of the script text file and click apply.

It gives us a UI, where we can upload the file to the document library.



Once we have browsed the required file, click Upload. It will upload the file to the document library.

Pitfall

Though we can upload the file to the document library using JavaScript object model, there is a pitfall that we should be aware of. JSOM has an inherent limitation that only files of sizes up to 5MB can be uploaded using this method. For bigger file size, we have to use REST to upload the file to the document library.

Up Next
    Ebook Download
    View all
    Learn
    View all