Get All Attachments From SharePoint List Item using Rest API and JavaScript Object Model (JSOM)

This SharePoint Rest API tutorial we will discuss how we can retrieve all attachments from a SharePoint 2013 list item using Rest API in SharePoint 2013. Here I have a list and each item has some attachments. We will try to retrieve all the attachments from a particular item using Rest API in SharePoint 2013/Online.

If you are new to Rest API, then check SharePoint Rest API Tutorial and Examples.

Get All Attachments From SharePoint 2013 List Item using Rest API

In this particular example, I am trying to retrieve attachments from list item whose id is 3.

Put the below code in a script editor web part or inside a content editor web part.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(‘MyTestList’)/items(3)/AttachmentFiles";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
var itemsCount = data.d.results.length;
alert (itemsCount);
if (data) {
$.each(data.d.results, function () {
// do something
alert( this.ServerRelativeUrl);
});
}
}

function onError(error) {
alert(JSON.stringify(error));
}
});

});

</script>

<input type="button" id="btnClick" value="Get Attachments"/>

Once you save the code and click on the button, it will display all the attachments in the alert dialog box in SharePoint Online or SharePoint 2013/2016.

Get All Attachments From SharePoint List Item using JavaScript Object Model (JSOM)

Now, we will discuss, how to get list item attachments using the JavaScript client object model (jsom) in SharePoint 2013/2016/Online.

Whenever a user does an attachment then the attachments are stored in an attachment folder and you can view that items attachment by URL:

{SITE URL}/Lists/{LIST NAME}/Attachments/{ITEM ID}/{ATTACHED FILE}

Example: http://<servername>/lists/MyTestList/Attachments/1/MyTestDoc.docx

Below is the JavaScript code to get all attachments from the SharePoint list item using JavaScript.

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getWebProperties, "SP.js");
var attachmentFiles;
function getWebProperties() {
var itemId=2;
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var attachmentFolder=web.getFolderByServerRelativeUrl(‘Lists/City/Attachments/’+itemId);

attachmentFiles= attachmentFolder.get_files();
ctx.load(attachmentFiles);
ctx.executeQueryAsync(Function.createDelegate(this,this.onSuccess),Function.createDelegate(this,this.onFailed));
}
function onSuccess(sender, args) {
var i=0;
for(var file in attachmentFiles)
{
alert(attachmentFiles.itemAt(i).get_serverRelativeUrl());
i++;
}
}
function onFailed(sender, args) {
alert("Something went Wrong");
}
</script>

Here, we discussed how to get all list item attachments using jsom (JavaScript object model) in SharePoint.

SharePoint rest api add attachment to list item

In this SharePoint tutorial, we will discuss how to add an attachment to list item using SharePoint rest API. Also, we will see:

  • SharePoint rest api add an attachment to list item
  • SharePoint rest api add multiple attachments to list item
  • How to display SharePoint list item attachments using REST API and jQuery
  • How to delete SharePoint List Item attachment using Rest API

SharePoint rest api add attachment to list item

Below is the step by step tutorial on how to upload an attachment to a new item on the list using Rest API in SharePoint 2013 or SharePoint Online.

The below code snippet will show the Personal Details HTML that has been created for the user to insert data into the list. In Html One tag highlighted to facilitate multi-file upload control, I am leveraging “jquery.multifile.js” plugin. If we don’t use that plugin, the user will select only one input file for upload.

<script type="text/javascript" src="/Script/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/Script/jquery-ui.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/Script/jquery.multifile.js"></script>

<span style="font-size: 22.0pt; padding-left: 20px">Personal Details<o:p></o:p></span>
<table align="left" border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" width="0" id="mytable">
<tbody>
<tr>
<td>
<table align="left" border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" style="">
<tbody>
<tr>
<td style="" valign="top" class="auto-style16">
<h3>Name</h3>
</td>
<td valign="top" style="padding: 9px;" class="auto-style17">
<input type="text" value="" maxlength="255" id="Name" title="Name" style="width: 96%;" class="ms-long ms-spellcheck-true">
</td>
</tr>
<tr>
<td class="auto-style16">
<h3>Address</h3>
</td>
<td class="auto-style17">
<input type="text" value="" maxlength="255" id=" Address" title="Address" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15">
<h3>City</h3>
</td>
<td class="auto-style4">
<input type="text" value="" maxlength="255" id=" City " title=" City " style="width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15">
<h3>Contact Number </h3>
</td>
<td class="auto-style5">
<input type="text" value="" maxlength="255" id=" ContactNumber " title="ContactNumber" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><span style="font-family: &quot; segoe ui&quot; ,sans-serif; color: #444444">Click here to attach file</span>
<div class="files" id="attachFilesHolder ">
<input id="file_input" type="file" name="files[]">
</div>
</td>
<td></td>
</tr>
</tbody>
</table>
<div style="text-align: -webkit-center; padding-bottom: 20px; padding-top: 20px; padding-left: 190px">
<input name="SaveItem" style="height: 40px; font-size: 15px;" class="ms-ButtonHeightWidth" id=" NewSaveItem " accesskey="O" onclick="" type="button" value="Click here to submit " target="_self">
</div>
</tbody>
</table>
sharepoint rest api add attachment to list item
sharepoint rest api add attachment to list item

Step-1: Navigate to your SharePoint 2013 site.

Step-2: From this page, select Site Actions | Edit Page.

Edit the page, go to the Insert tab in the Ribbon and click the Web Part option. In the Web Parts picker area, go to the Media and Content category, select the Script Editor Web Part and press the Add button.

Step-3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

<script type="text/javascript">
var arraycount = 0;
var fileUploadeCount = 0;
$(document).ready(function ($) {
$(‘#file_input’).multifile();
$("#NewSaveItem").click(function () { formSave() });
});
function formSave() {
var listItem = "";
var fileArray = [];
$("#attachFilesHolder input:file").each(function () {
if ($(this)[0].files[0]) {
fileArray.push({ "Attachment": $(this)[0].files[0] });
}
});

arraycount = fileArray.length;
listItem = {
__metadata: { "type": "SP.Data.BankDetailsListItem" },
"Name": $("input[title=’Name’]").val(),
"Address ": $("input[title=’Address’]").val(),
"City": $("input[title= City]").val(),
"ContactNumber": $("input[title=’ContactNumber’]").val(),
"Files": fileArray
};
createItemparent("BankDetails", filesarray, listItem);
}

function createNewItem(listname, filearray, listItem) {
var dfd = $.Deferred();
var initializePermsCall = PostAjax(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle(‘" + listname + "‘)/items", listItem);
$.when(initializePermsCall).then(function (permData) {
var id = permData.d.Id;
if (filearray.length != 0) {
for (i = 0; i <= filearray.length – 1; i++) {
loopFileUpload(listname, id, filearray, i).then(
function () {
},

function (sender, args) {
console.log("Error uploading");
dfd.reject(sender, args);
}
);
}
}
});
}

function PostAjax(siteurl, listItem) {
return $.ajax({
url: siteurl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(listItem),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
});
}

function loopFileUpload(listName, id, filearray, fileCount) {
var dfd = $.Deferred();
uploadFile(listName, id, filearray[fileCount].Attachment); return dfd.promise();
}

function uploadFile(listname, ID, file) {
var getFileBuffer = function (file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
};

getFileBuffer(file).then(function (buffer) {

$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(‘" + listname + "‘)/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "‘)",
method: ‘POST’,
async: false,
data: buffer,
processData: false,
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
}, success: onAttachmentSucess
});
});

function onAttachmentSucess() {
fileUploadeCount++;
if (arraycount == fileUploadeCount) {
console.log(data + ‘ uploaded successfully’);
}
}
}

</script>

Final Output:

sharepoint rest api add attachment to list item
sharepoint rest api add attachment to list item

This is how to upload multiple files to sharepoint list item using rest api.

SharePoint rest api add multiple attachments to list item

Let us see how to add multiple attachments to list item in SharePoint rest api.

The below code snippet will show the Personal Details HTML that has been created for the user to insert data into the list. In Html One tag highlighted to facilitate multi-file upload control, I am leveraging “jquery.multifile.js” plugin. If we don’t use that plugin, the user will select only one input file for upload.

<script type="text/javascript" src="/Script/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/Script/jquery-ui.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/Script/jquery.multifile.js"></script>
<span style="font-size: 22.0pt; padding-left: 20px">Personal Details<o:p></o:p></span>

<table align="left" border="1″ cellpadding="0″ cellspacing="0″ class="MsoTableGrid" width="0″ id="mytable">
<tbody>
<tr>
<td>
<table align="left" border="1″ cellpadding="0″ cellspacing="0″ class="MsoTableGrid" style="">
<tbody>
<tr>
<td style="" valign="top" class="auto-style16″>
<h3>Name</h3>
</td>
<td valign="top" style="padding: 9px;" class="auto-style17″>
<input type="text" value="" maxlength="255″ id="Name" title="Name" style="width: 96%;" class="ms-long ms-spellcheck-true">
</td>
</tr>
<tr>
<td class="auto-style16″>
<h3>Address</h3>
</td>
<td class="auto-style17″>
<input type="text" value="" maxlength="255″ id=" Address" title="Address" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15″>
<h3>City</h3>
</td>

<td class="auto-style4″>
<input type="text" value="" maxlength="255″ id=" City " title=" City " style="width: 96%;" class="ms-long ms-spellcheck-true"></td>
</tr>
<tr>
<td class="auto-style15″>

<h3>Contact Number </h3>
</td>
<td class="auto-style5″>
<input type="text" value="" maxlength="255″ id=" ContactNumber " title="ContactNumber" style="ime-mode: ; width: 96%;" class="ms-long ms-spellcheck-true">
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><span style="font-family: &quot; segoe ui&quot; ,sans-serif; color: #444444″>Click here to attach file</span>
<div class="files" id="attachFilesHolder ">
<input id="file_input" type="file" name="files[]">
</div>
</td>
<td></td>
</tr>
</tbody>
</table>

<div style="text-align: -webkit-center; padding-bottom: 20px; padding-top: 20px; padding-left: 190px">
<input name="SaveItem" style="height: 40px; font-size: 15px;" class="ms-ButtonHeightWidth" id=" NewSaveItem " accesskey="O" onclick="" type="button" value="Click here to submit" target="_self">
</div>
</tbody>
</table>
upload multiple attachments to sharepoint list item using rest api
upload multiple attachments to sharepoint list item using rest api

Step-1: Navigate to your SharePoint 2013 site. From this page, select Site Actions -> Edit Page.

Edit the page, go to the Insert tab in the Ribbon, and click on the Web Part option. In the Web Parts picker area, go to the Media and Content category, select the Script Editor Web Part, and press the Add button.

Step-2: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

<script type="text/javascript">
var oLoader;
var attcount = 0;
var arraycount = 0;
$(document).ready(function ($) {
$(‘#file_input’).multifile();//For facilitate multi file upload
$("#NewSaveItem").click(function () { formSave() });
});
function formSave() {
oLoader = SP.UI.ModalDialog.showWaitScreenWithNoClose("Working on it", "Creating New Bank Account…");
for (i = 0; i < count; i++) {
var data = [];
var fileArray = [];
$("#attachFilesHolder input:file").each(function () {
if ($(this)[0].files[0]) {
fileArray.push({ "Attachment": $(this)[0].files[0] });
}
});
data.push({
"Name": $("input[title=’Name’]").val(),
" Address ": $("input[title=’Address’]").val(),
"City": $("input[title= City]").val(),
"ContactNumber": $("input[title=’ContactNumber’]").val(),
"Files": fileArray
});
createNewItemWithAttachments("BankDetails", data).then(
function () {
if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.siteAbsoluteUrl + "/Lists/BankDetails/AllItems.aspx"); }, 3000);
},
function (sender, args) {
console.log(‘Error occured’ + args.get_message());
}
)
}
}
var createNewItemWithAttachments = function (listName, listValues) {
var fileCountCheck = 0;
var fileNames;
var context = new SP.ClientContext.get_current();
var dfd = $.Deferred();
var targetList = context.get_web().get_lists().getByTitle(listName);
context.load(targetList);
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = targetList.addItem(itemCreateInfo);
listItem.set_item("Name", listValues[0].Name);
listItem.set_item("Address", listValues[0].Address);
listItem.set_item("City", listValues[0].City);
listItem.set_item("ContactNumber", listValues[0].ContactNumber);
listItem.update();
context.executeQueryAsync(
function () {
var id = listItem.get_id();
if (listValues[0].Files.length != 0) {
if (fileCountCheck <= listValues[0].Files.length – 1) {
loopFileUpload(listName, id, listValues, fileCountCheck).then(
function () {
},
function (sender, args) {
console.log("Error uploading");
dfd.reject(sender, args);
}
);
}
}
else {
dfd.resolve(fileCountCheck);
}
},
function (sender, args) {
console.log(‘Error occured’ + args.get_message());
}
);
return dfd.promise();
}
function loopFileUpload(listName, id, listValues, fileCountCheck) {
var dfd = $.Deferred();
uploadFileHolder(listName, id, listValues[0].Files[fileCountCheck].Attachment).then(
function (data) {
var objcontext = new SP.ClientContext();
var targetList = objcontext.get_web().get_lists().getByTitle(listName);
var listItem = targetList.getItemById(id);
objcontext.load(listItem);
objcontext.executeQueryAsync(function () {
console.log("Reload List Item- Success");
fileCountCheck++;
if (fileCountCheck <= listValues[0].Files.length – 1) {
loopFileUpload(listName, id, listValues, fileCountCheck);
} else {
console.log(fileCountCheck + ": Files uploaded");
attcount += fileCountCheck;
if (arraycount == attcount) {
if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.siteAbsoluteUrl + "/Lists/BankDetails/AllItems.aspx"); }, 3000);
}
}
},
function (sender, args) {
console.log("Reload List Item- Fail" + args.get_message());
});
},
function (sender, args) {
console.log("Not uploaded");
dfd.reject(sender, args);
}
);
return dfd.promise();
}

function uploadFileHolder(listName, id, file) {
var deferred = $.Deferred();
var fileName = file.name;
getFileBuffer(file).then(
function (buffer) {
var bytes = new Uint8Array(buffer);
var binary = ";
for (var b = 0; b < bytes.length; b++) {
binary += String.fromCharCode(bytes[b]);
}
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
console.log(‘ File size:’ + bytes.length);
$.getScript(scriptbase + "SP.RequestExecutor.js", function () {
var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
createitem.executeAsync({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle(‘" + listName + "‘)/items(" + id + ")/AttachmentFiles/add(FileName=’" + file.name + "‘)",
method: "POST",
binaryStringRequestBody: true,
body: binary,
success: fsucc,
error: ferr,
state: "Update"
});

function fsucc(data) {
console.log(data + ‘ uploaded successfully’);
deferred.resolve(data);
}

function ferr(data) {
console.log(fileName + "not uploaded error");
deferred.reject(data);
}
});
},
function (err) {
deferred.reject(err);
}
);
return deferred.promise();
}

function getFileBuffer(file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
}
</script>
Rest API upload multiple attachment to list item SharePoint Online
Rest API upload multiple attachment to list item SharePoint Online

This is how we can add multiple attachments in sharepoint list using rest api.

Display SharePoint list item attachments using REST API and jQuery

Let us see how to show the SharePoint list item attachments using REST API and jQuery. We will use Rest API to display list item attachments in SharePoint Online or SharePoint 2013/2016/2019.

Now let’s use some REST API to pull these attachments and display them in list.

For retrieving attachments I am using REST API, URL for all attachments collection can be built like below

{Site URL}/_api/web/lists/getbytitle([List Title])/items([item ID])/AttachmentFiles

I have created a custom list in the host site named “Attachment“. Adding multiple items with attachments and let’s say that we want to show the item level attachments on the item selection.

Display SharePoint list item attachments using REST API
Display SharePoint list item attachments using REST API

I have an item (Item ID: 1) that has the following attachments.

Display SharePoint Online list item attachments using REST API
Display SharePoint Online list item attachments using REST API

I wanted to get the URLs of the list item attachments so that I could use it in my HTML. To fetch the Item ID of the list item and bind to dropdown. Once we have selected any Item ID from the list of Item IDs from Dropdown, the attachments of the respective item are shown. An on-change event is used to fetch and we show the related attachments.

Use the procedure given below.

Step-1: Navigate to your SharePoint 2013 site.

Step-2: From this page, select Site Actions | Edit Page.

Edit the page, go to the Insert tab in the Ribbon and click the Web Part option. In the Web Parts picker area, go to the Media and Content category, select the Script Editor Web Part and press the Add button.

Step-3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

<script type="text/javascript" src="../../SiteAssets/Script/jquery-1.9.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function ($) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments')/items?$select=Id";
getListItems(url, function (data) {
var items = data.d.results;
var SelectElement = '<select id="drpListItem" style="width:100%" name="options"><option value="">Select</option>';

// Add all the Item Id in Dropdown
for (var i = 0; i < items.length; i++) {
var itemId = items[i].Id;
SelectElement += '<option value="' + itemId + '"selected>' + itemId + '</option>';
}

SelectElement += '</select>';
$('#ItemID').append(SelectElement);
// assign the change event
$('#drpListItem').on('change', function () {
if ($(this).val() != "") {
var Requestorurl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments')/items(" + $(this).val() + ")/AttachmentFiles";
getListItems(Requestorurl, function (data) {
var results = data.d.results;
var htmlStr = "";
if (data.d.results.length > 0) {
$.each(data.d.results, function () {
if (htmlStr === "") {
htmlStr = "<li><a id='attachment' href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></li>";
}
else {
htmlStr = htmlStr + "<li><a id='attachment' href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></li>";
}
});
}
else { htmlStr = "<strong>There are no attachments to show in this item.<strong>"; }
$('#attachmentsContainer').html(htmlStr);
});
}
});
}, function (data) {
console.log("An error occurred. Please try again.");
});

});

function getListItems(siteurl, success, failure) {
$.ajax({
url: siteurl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},

error: function (data) {
failure(data);
}
});
}
</script>

Final Output:

List Item with Attachments:

display sharepoint list item attachments using rest api
display sharepoint list item attachments using rest api

List item without Attachments:

display SharePoint 2013 list item attachments using REST API
display SharePoint 2013 list item attachments using REST API

The above code we can use to display SharePoint list item attachments using REST API and jQuery in SharePoint 2013/2016/2019 or SharePoint Online.

Delete SharePoint List Item attachment using Rest API

Let us discuss, how to delete SharePoint list item attachments using REST API and jQuery in SharePoint 2013/2016/2019 or SharePoint Online.

To remove attachments I am using REST API, to delete only specific attachments (based on the attached file name and list Item) we need to build a URL as shown below:

{SiteURL}/_api/web/lists/GetByTitle([ListTitle])/GetItemById([ItemID])/AttachmentFiles/getByFileName([ FileTitle ])

I have created a custom list named “Attachments” in the host site and have added multiple items with attachments, now let’s say that we want to “Delete” the attachments on any particular item which we want.

delete sharepoint list item attachment using rest api
delete sharepoint list item attachment using rest api

I have an item (Item ID: 1) that has the following attachments.

delete list item attachment using rest api in sharepoint online
delete list item attachment using rest api in sharepoint online

I wanted to get the URLs of the list item attachments with delete option so that I could use it in my html. To fetch the Item ID of the list item and bind to dropdown. Once we have selected any Item ID from the list of Item IDs from Dropdown, the attachments of the respective item are shown. Click on X (Delete icon) to Delete the Attachment on the item.

Below is the step by step tutorial on how to delete SharePoint List Item attachment using Rest API.

Step-1: Navigate to your SharePoint 2013 site.

Step-2: From this page, select Site Actions | Edit Page.

Edit the page, go to the Insert tab in the Ribbon and click Web Part option. In the Web Parts picker area, go to the Media and Content category, select the Script Editor Web Part and press the Add button.

Step-3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

<script type="text/javascript" src="../../SiteAssets/Script/jquery-1.9.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function ($) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments’)/items?$select=Id";
getListItems(url, function (data) {
var items = data.d.results;
var SelectElement = '<select id="drpListItem" style="width:100%" name="options"><option value="">Select</option>’;
// Add all the Item Id in Dropdown
for (var i = 0; i < items.length; i++) {
var itemId = items[i].Id;
SelectElement += '<option value="' + itemId + '"selected>’ + itemId + '</option>’;
}
SelectElement += '</select>’;
$('#ItemID’).append(SelectElement);
// assign the change event
$('#drpListItem’).on('change’, function () {
if ($(this).val() != "") {
var Requestorurl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Attachments’)/items(" + $(this).val() + ")/AttachmentFiles";
var ID = $(this).val();
getListItems(Requestorurl, function (data) {
var results = data.d.results;
var htmlattach = "";
if (data.d.results.length > 0) {
$.each(data.d.results, function () {
if (htmlattach === "") {
htmlattach = "<p class=’uploaded_image’> <a href=’javascript:void(0);’ id='" + ID + "' class=’remove’>&times;</a> <span class=’filename’><a id=’attachment’ href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></span></p>";
}
else {
htmlattach = htmlattach + "<p class=’uploaded_image’> <a href=’javascript:void(0);’ id='" + ID + "' class=’remove’>&times;</a> <span class=’filename’><a id=’attachment’ href='" + this.ServerRelativeUrl + "'>" + this.FileName + "</a></span></p>";
}
});
}
else { htmlattach = "<strong>There are no attachments to in this item.<strong>"; }
$('#attachmentsContainer’).html(htmlattach);
});
}
});
}, function (data) {
console.log("An error occurred. Please try again.");
});
$(document).on("click", "a.remove", function () {
DeleteItemAttachment($(this).attr('id’), $(this).next('span’).text());
$(this).parent().remove();
});
});
function getListItems(siteurl, success, failure) {
$.ajax({
url: siteurl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}

function DeleteItemAttachment(ItemId, FileTitle) {
var Dfd = $.Deferred();
var Url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Attachments’)/GetItemById(" + ItemId + ")/AttachmentFiles/getByFileName('" + FileTitle + "') ";
$.ajax({
url: Url,
type: 'DELETE’,
contentType: 'application/json;odata=verbose’,
headers: {
'X-RequestDigest’: $('#__REQUESTDIGEST’).val(),
'X-HTTP-Method’: 'DELETE’,
'Accept’: 'application/json;odata=verbose’
},

success: function (data) {
Dfd.resolve(data);
},
error: function (error) {
Dfd.reject(JSON.stringify(error));
}
});
return Dfd.promise();
}
</script>

In the below screen shot we have delete “Account.doc” File on click X (Delete icon).

delete list item attachment using rest api in sharepoint
delete list item attachment using rest api in sharepoint

Final Output:

delete sharepoint list item attachment using rest api
delete sharepoint list item attachment using rest api
delete attachments of SharePoint list item using REST API
delete attachments of SharePoint list item using REST API

The above rest api code we can use to delete list item attachments using Rest API in SharePoint 2019/2016/2013 or SharePoint Online.

You may also like following SharePoint Rest API tutorials:

Hope this SharePoint tutorial helps to get all attachments from a SharePoint list item using Rest API.

I hope this SharePoint Rest API tutorial helps to upload multiple files to sharepoint list item using rest API and the below things:

  • SharePoint rest api add an attachment to list item
  • SharePoint rest api add multiple attachments to list item
  • How to display SharePoint list item attachments using REST API and jQuery
  • How to delete SharePoint List Item attachment using Rest API
>