Create Attachment Folder For SharePoint List Item In Office 365 Using JavaScript Object Model

SharePoint Lists are one of the primary content repositories where we can store list items. Lists are highly useful, because they allow us to attach the files as well. One of the major advantages over SharePoint libraries is that we can attach multiple files in to a SharePoint list item. However, we have the flexibility to change the list item attachment settings from List settings->Advanced Settings.



We can add the attachment to the list item out of the box, as shown below:



Whenever an attachment is added internally, it creates an attachment folder for each item it is attached to. If there is no attachment for a list item, it won’t be having 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. First is the folder name that is created with the name as List item ID. If there are no attachments for a list item, we would get the error, shown below, if the attachment folder is accessed.



Let’s see how we can create an attachment folder, using JavaScript Object model, so that we can add attachments programmatically later on.

  • 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 . Call the main starting point function, say:checkAttachmentFolder.
    1. SP.SOD.executeFunc('sp.js''SP.ClientContext', checkAttachmentFolder);  
  • Instantiate the client context and get the list instance. Once the list object is retrieved; break inheritance of the object.
    1. clientContext= new SP.ClientContext();  
    2. oWeb= clientContext.get_web();  
    3.   
    4. varoList= oWeb.get_lists().getByTitle('NewList');  
    5. oListItem= oList.getItemById(1);  
  • 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(oWeb);  
    2. clientContext.load(oListItem);  
    3. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  • When successful, call back method and define attachment folder creation:
    1. varattachmentsFolder= oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments');  
    2. varattachmentsFolderURL=  
    3. oWeb.get_serverRelativeUrl()+'Lists/NewList/Attachments';    
    4. attachmentsFolder= attachmentsFolder.get_folders().add('_' + '1');  
    5. attachmentsFolder.moveTo(attachmentsFolderURL+ '/' + '1');  
  • Load the client context and execute the batch once again so as to create the attachment folder.

Output

Now, if we navigate to https://SiteURL/sites/Playground/Lists/ListName/Attachments/1 , we will be able to see the newly created attachment folder.



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

  • Save the code given below to a text file and save it into one of the SharePoint libraries, say: Site Assets.
    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">  
    3.     varfileInput;      $(document).ready(function()  
    4.     {  
    5.         SP.SOD.executeFunc('sp.js''SP.ClientContext', checkAttachmentFolder);  
    6.     });  
    7.     varclientContext, oListItem, oWeb;  
    8.   
    9.     function checkAttachmentFolder()  
    10.     {  
    11.   
    12.         //Get Client Context and Web object.  
    13.         clientContext = new SP.ClientContext();  
    14.         oWeb = clientContext.get_web();  
    15.   
    16.         //Get list and Attachment folder where the attachment of a particular list item is stored.  
    17.         varoList = oWeb.get_lists().getByTitle('NewList');  
    18.         oListItem = oList.getItemById(1);  
    19.   
    20.         //Load client context and execute the batch  
    21.         clientContext.load(oWeb);  
    22.         clientContext.load(oListItem);  
    23.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
    24.     }  
    25.   
    26.     function QuerySuccess()  
    27.     {  
    28.         if (!oListItem.get_fieldValues()['Attachments'])  
    29.         {  
    30.             //Get attachment folder and attachment folderrurl  
    31.             varattachmentsFolder = oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments');  
    32.             varattachmentsFolderURL = oWeb.get_serverRelativeUrl() + 'Lists/NewList/Attachments';  
    33.   
    34.             //Create Attachment Folder   
    35.             attachmentsFolder = attachmentsFolder.get_folders().add('_' + '1');  
    36.             attachmentsFolder.moveTo(attachmentsFolderURL + '/' + '1');  
    37.   
    38.             //Load Client Context and execute the batch  
    39.             clientContext.load(attachmentsFolder);  
    40.             clientContext.executeQueryAsync(SecondQuerySuccess, SecondQueryFailure);  
    41.         }  
    42.     }  
    43.   
    44.     function QueryFailure(sender, args)  
    45.     {  
    46.         console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
    47.     }  
    48.   
    49.     function SecondQuerySuccess(sender, args)  
    50.     {  
    51.         console.log('Attachment folder has been created.');  
    52.     }  
    53.   
    54.     function SecondQueryFailure(sender, args)  
    55.     {  
    56.         console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
    57.     }  
    58. </script>  
  • Go to the edit settings of the SharePoint page and click Web part from the insert tab,



  • Add Content Editor Web part.



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


Now, if we navigate to the attachment folder of the list item- /Lists/ListName/Attachments/ItemID, we can view an attachment folder with zero attachments.



We can later upload the attachments to this list item attachment folder programmatically, using JSOM as well as REST. If we try to upload an attachment to a list item for the first time programmatically, there won’t be an attachment folder and it will throw an error. Hence, it is important to check if the attachment folder exists for the list item before uploading an attachment to it.