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.
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,
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <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.
- 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.
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
-
-
- var attachmentFolder=
- oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');
- 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.
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- In the success call back method, get the attachment file enumerator and loop through it.
- var attachmentEnumerator = attachmentFiles.getEnumerator();
- while (attachmentEnumerator.moveNext())
- {
- console.log(attachmentEnumerator.get_current().get_name());
- }
Output
Full Code
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- $(document).ready(function()
- {
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getListAttachments);
- });
- var attachmentFiles;
-
- function getListAttachments()
- {
- //get client context and web
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- //Get the attachment folder for the list item and get the attachment collection
- var attachmentFolder = oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');
- attachmentFiles = attachmentFolder.get_files();
- //Load the client context and execute the batch
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
-
- function QuerySuccess()
- {
- // get the attachment collection and loop through it
- var attachmentEnumerator = attachmentFiles.getEnumerator();
- while (attachmentEnumerator.moveNext())
- {
- console.log(attachmentEnumerator.get_current().get_name());
- }
- }
-
- function QueryFailure(sender, args)
- {
- console.log('Request failed - ' + args.get_message());
- }
- </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.
- var attachmentFolder=
- oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');
- attachmentFiles= attachmentFolder.get_files();
- Load the client context and execute the batch so that the file collection can be retrieved from the server.
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- Get the attachment file enumerator and loop through it. Use deleteObject to delete the attachment file.
- var attachmentEnumerator = attachmentFiles.getEnumerator();
- while (attachmentEnumerator.moveNext())
- var fileName = attachmentEnumerator.get_current().get_name();
- if (fileName == "Fields.docx")
- {
- deleteAttachment = attachmentEnumerator.get_current();
- }
- deleteAttachment.deleteObject();
- Call clientContext.executeQueryAsync once again to execute the batch.
Full Code
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- $(document).ready(function()
- {
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', deleteFileAttachment);
- });
- var attachmentFiles, clientContext;
-
- function deleteFileAttachment()
- {
-
- //Get the clientcontext and web object
- clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
-
- //Get attachment folder for the list item
- var attachmentFolder = oWeb.getFolderByServerRelativeUrl('Lists/Custom/Attachments/1');
- attachmentFiles = attachmentFolder.get_files();
-
- //Load clientcontext and execute the batch
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
-
- function QuerySuccess()
- {
- var deleteAttachment;
- //Loop through the attachments and delete the attachments
- var attachmentEnumerator = attachmentFiles.getEnumerator();
- while (attachmentEnumerator.moveNext())
- {
- var fileName = attachmentEnumerator.get_current().get_name();
- if (fileName == "Fields.docx")
- {
- deleteAttachment = attachmentEnumerator.get_current();
- }
- }
- deleteAttachment.deleteObject();
- //Execute the batch
- clientContext.executeQueryAsync(SecondQuerySuccess, SecondQueryFailure);
- }
-
- function QueryFailure(sender, args)
- {
- console.log('Request failed - ' + args.get_message());
- }
-
- function SecondQuerySuccess()
- {
- console.log("Attachment Deleted.");
- }
-
- function SecondQueryFailure(sender, args)
- {
- console.log('Request failed - ' + args.get_message());
- }
- </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.
- Add Content Editor Web part, shown below:
- Click Edit Web art from Content Edit Web part. Assign the URL of the script text file and click apply.
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.