Upload File To List Item In Office 365 As An Attachment Using JavaScript Object Model

It is rather a common scenario, where we might have a requirement to upload a file to a SharePoint List as an attachment. SharePoint provides the flexibility to upload multiple attachments to a specific list item, contrary to the library functionality of a single document upload per item. We can add an attachment to the list item out of the box, if the list settings permits the user to do so.

attachment

If enabled, we can attach the multiple attachments to a particular list item.

attachments

Whenever an attachment is added, internally, SharePoint creates an attachment folder for each item it is attached to. If there is no attachment for a list item, it won’t have an attachment folder. The attachment folder for a particular item will be located at the URL given below:

https://SiteURL/sites/Playground/Lists/ListName/Attachments/1

ListName is the name of the list. ‘1’ is the folder name that is created with the name as List item ID.

Let’s see how we can implement uploading of the attachments to the list item, using JavaScript Object Model,

  • 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 the document, call ready function SP.SOD.executeFunc, so as to load the on demand 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. var reader = 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. clientContext = new SP.ClientContext();  
    2. var oWeb = clientContext.get_web();  
    3. //Get list and Attachment folder where the attachment of a particular list item is stored  
    4. var oList = oWeb.get_lists().getByTitle('NewList');  
    5. var attachmentFolder=oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments/1');  
  • Convert the file contents into base64 data,
    1. var bytes = new Uint8Array(arrayBuffer);  
    2. var i, length, out = '';  
    3. for (i = 0, length = bytes.length; i < length; i += 1)   
    4. {  
    5.     out += String.fromCharCode(bytes[i]);  
    6. }  
    7. var base64 = btoa(out);  
  • Create FileCreationInformation object, using the read file data,
    1. createInfo = new SP.FileCreationInformation();  
    2. createInfo.set_content(base64);  
    3. createInfo.set_url(fileName);  
    4. //Add the file to the list item  
    5. attachmentFiles = attachmentFolder.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(oList);  
    2. clientContext.load(attachmentFiles);  
    3. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  

We can test this in SharePoint by adding it to the Content Editor Web part.

  • Save the code given below to a text file and save it into one of the SharePoint libraries say: Site Assets
    1. <html>  
    2.   <head>  
    3.     <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    4.     <script language="javascript" type="text/javascript">  
    5.         var fileInput;  
    6.         $(document).ready(function()   
    7.         {  
    8.             fileInput = $("#getFile");  
    9.             SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);  
    10.         });  
    11.   
    12.         function registerClick()   
    13.         {  
    14.             //Register File Upload Click Event  
    15.             $("#addFileButton").click(readFile);  
    16.         }  
    17.         var arrayBuffer;  
    18.   
    19.         function readFile()   
    20.         {  
    21.             //Get File Input Control and read th file name  
    22.             var element = document.getElementById("getFile");  
    23.             var file = element.files[0];  
    24.             var parts = element.value.split("\\");  
    25.             var fileName = parts[parts.length - 1];  
    26.             //Read File contents using file reader  
    27.             var reader = new FileReader();  
    28.             reader.onload = function(e) {  
    29.                 uploadFile(e.target.result, fileName);  
    30.             }  
    31.             reader.onerror = function(e)   
    32.             {  
    33.                 alert(e.target.error);  
    34.             }  
    35.             reader.readAsArrayBuffer(file);  
    36.         }  
    37.         var attachmentFiles, clientContext, createInfo;  
    38.   
    39.         function uploadFile(arrayBuffer, fileName)   
    40.         {  
    41.             //Get Client Context and Web object.  
    42.             clientContext = new SP.ClientContext();  
    43.             var oWeb = clientContext.get_web();  
    44.   
    45.             //Get list and Attachment folder where the attachment of a particular list item is stored.  
    46.             var oList = oWeb.get_lists().getByTitle('NewList');  
    47.             var attachmentFolder = oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments/1');  
    48.   
    49.             //Convert the file contents into base64 data  
    50.             var bytes = new Uint8Array(arrayBuffer);  
    51.             var i, length, out = '';  
    52.             for (i = 0length = bytes.length; i < length; i += 1) {  
    53.                 out += String.fromCharCode(bytes[i]);  
    54.             }  
    55.             var base64 = btoa(out);  
    56.             //Create FileCreationInformation object using the read file data  
    57.             createInfo = new SP.FileCreationInformation();  
    58.             createInfo.set_content(base64);  
    59.             createInfo.set_url(fileName);  
    60.   
    61.             //Add the file to the list item  
    62.             attachmentFiles = attachmentFolder.get_files().add(createInfo);  
    63.   
    64.             //Load client context and execute the batch  
    65.             clientContext.load(oList);  
    66.             clientContext.load(attachmentFiles);  
    67.             clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
    68.         }  
    69.   
    70.         function QuerySuccess()   
    71.         {  
    72.             console.log("Attachment added successfuly ");  
    73.         }  
    74.   
    75.         function QueryFailure(sender, args)   
    76.         {  
    77.             console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
    78.         }  
    79.     </script>  
    80. </head>  
    81.   
    82. <body>  
    83.     <input id="getFile" type="file" /><br />  
    84.     <input id="addFileButton" type="button" value="Upload" />  
    85. </body>  
    86. <html>  
  • Go to the edit settings of the SharePoint page and click Web part from the Insert tab.

    Web part

  • Add Content Editor Web part.

    Add Content

  • Click Edit Web art from Content Edit Web part. Assign the URL of the script text file and click Apply.

    Apply

  • Now Click Apply. It gives us a UI from where we can upload the file as an attachment to SharePoint Llst item.

    choose

Once we browse and click on upload it will upload the attachment file to the specified List Item.

file

Thus, we have seen how we can upload a list item as an attachment to a SharePoint list Item.

Pitfall

However, there is a limitation for this method. JavaScript object model allows only the upload of the files, which are less than or equal to 5 MB in size. Any file above the file limit cannot be uploaded using JSOM. Instead, we will have to use REST to perform the upload, which will be covered in an upcoming article.

Up Next
    Ebook Download
    View all
    Learn
    View all