Retrieve and Delete Attachment Files In SharePoint 2016 And Office 365 Using JavaScript Object Model

SharePoint lists are designed to have multiple attachments added to a list item. Whenever an attachment is added to a list item it internally creates an attachment folder. 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:

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

‘ListName’ is the name of the list. ‘Attachments’ is the folder for all the attachments within the list.’ 1’ 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, when the attachment folder is accessed.

page

Let’s see how we can read the attachments files and delete them using JavaScript Object Model.

Retrieve Attachment Files

  • 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: getListAttachments.
    1. SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getListAttachments);  
  • Instantiate client context and get the Web instance. Once the Web object is retrieved, get the attachment folder object and the attachment files collection.
    1. var clientContext = new SP.ClientContext();  
    2. var oWeb = clientContext.get_web();  
    3.   
    4. //Get the attachment folder for the list item and get the attachment collection  
    5. var attachmentFolder=  
    6. oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');  
    7. attachmentFiles= attachmentFolder.get_files();  
  • 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(attachmentFiles);  
    2. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  • In the success call back method, get the attachment file enumerator and loop through it.
    1. var attachmentEnumerator = attachmentFiles.getEnumerator();  
    2. while (attachmentEnumerator.moveNext())   
    3. {  
    4.     console.log(attachmentEnumerator.get_current().get_name());  
    5. }  
    Output

    Output

    Full Code
    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.     $(document).ready(function()  
    4.     {  
    5.         SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getListAttachments);  
    6.     });  
    7.     var attachmentFiles;  
    8.   
    9.     function getListAttachments()  
    10.     {  
    11.         //get client context and web  
    12.         var clientContext = new SP.ClientContext();  
    13.         var oWeb = clientContext.get_web();  
    14.         //Get the attachment folder for the list item and get the attachment collection  
    15.         var attachmentFolder = oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');  
    16.         attachmentFiles = attachmentFolder.get_files();  
    17.         //Load the client context and execute the batch  
    18.         clientContext.load(attachmentFiles);  
    19.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
    20.     }  
    21.   
    22.     function QuerySuccess()  
    23.     {  
    24.         // get the attachment collection and loop through it  
    25.         var attachmentEnumerator = attachmentFiles.getEnumerator();  
    26.         while (attachmentEnumerator.moveNext())   
    27.         {  
    28.             console.log(attachmentEnumerator.get_current().get_name());  
    29.         }  
    30.     }  
    31.   
    32.     function QueryFailure(sender, args)  
    33.     {  
    34.         console.log('Request failed - ' + args.get_message());  
    35.     }  
    36.  </script>  

Delete Attachment file

Once the list attachment object is retrieved, the list attachments can be deleted, using the ‘deleteObject’ method in JavaScript Object Model.

  • Get the file attachment folder object and the attachment file collection within it.
    1.  var attachmentFolder=  
    2.  oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');  
    3. attachmentFilesattachmentFolder.get_files();  
  • Load the client context and execute the batch so that the file collection can be retrieved from the server.
    1. clientContext.load(attachmentFiles);  
    2. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  • Get the attachment file enumerator and loop through it. Use deleteObject to delete the attachment file.
    1. var attachmentEnumerator = attachmentFiles.getEnumerator();  
    2. while (attachmentEnumerator.moveNext())  
    3.     var fileName = attachmentEnumerator.get_current().get_name();  
    4. if (fileName == "Fields.docx")  
    5. {  
    6.     deleteAttachment = attachmentEnumerator.get_current();  
    7. }   
    8. deleteAttachment.deleteObject();  
  • Call clientContext.executeQueryAsync once again to execute the batch.

    Full Code
    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.     $(document).ready(function()  
    4.     {  
    5.         SP.SOD.executeFunc('sp.js', 'SP.ClientContext', deleteFileAttachment);  
    6.     });  
    7.     var attachmentFiles, clientContext;  
    8.   
    9.     function deleteFileAttachment()  
    10.     {  
    11.   
    12.         //Get the clientcontext and web object   
    13.         clientContext = new SP.ClientContext();  
    14.         var oWeb = clientContext.get_web();  
    15.   
    16.         //Get attachment folder for the list item  
    17.         var attachmentFolder = oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');  
    18.         attachmentFiles = attachmentFolder.get_files();  
    19.   
    20.         //Load clientcontext and execute the batch  
    21.         clientContext.load(attachmentFiles);  
    22.         clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
    23.     }  
    24.   
    25.     function QuerySuccess()  
    26.     {  
    27.         var deleteAttachment;  
    28.         //Loop through the attachments and delete the attachments  
    29.         var attachmentEnumerator = attachmentFiles.getEnumerator();  
    30.         while (attachmentEnumerator.moveNext())  
    31.         {  
    32.             var fileName = attachmentEnumerator.get_current().get_name();  
    33.             if (fileName == "Fields.docx")  
    34.             {  
    35.                 deleteAttachment = attachmentEnumerator.get_current();  
    36.             }  
    37.         }  
    38.         deleteAttachment.deleteObject();  
    39.         //Execute the batch  
    40.         clientContext.executeQueryAsync(SecondQuerySuccess, SecondQueryFailure);  
    41.     }  
    42.   
    43.     function QueryFailure(sender, args)  
    44.     {  
    45.         console.log('Request failed - ' + args.get_message());  
    46.     }  
    47.   
    48.     function SecondQuerySuccess()  
    49.     {  
    50.         console.log("Attachment Deleted.");  
    51.     }  
    52.   
    53.     function SecondQueryFailure(sender, args)  
    54.     {  
    55.         console.log('Request failed - ' + args.get_message());  
    56.     }  
    57. </script>  

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

  • Save the code given 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 the Web part from the Insert tab.

    Web part

  • Add Content Editor Web part, shown below:

    Add

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

    Edit Web art

Now, click apply. This will delete the attachment files. We can use the script to fetch and retrieve the attachment files in a similar way to get the list of the attachment files in the console.

Thus, we have seen how to retrieve the attachment files of a SharePoint list item as well as to delete the specific attachment files, using JavaScript Object Model. This has been tested with SharePoint 2016 and Office 365.