How to: Get list item attachments using REST and JavaScript in SharePoint 2013
Posted
Thursday, June 27, 2013 2:26 PM
by
CoreyRoth
If you’re like me, you like complete code samples. I don’t like having to infer the code I am supposed to right when I see a reference in the API. I don’t program much any more, so I admit I am lazy and want to see a complete example that I know works. Yesterday, I wanted to get the URL of a list item attachment so I could bind it to an img tag. The Basic Operations with SharePoint 2013 REST endpoints post does a pretty good job explaining a lot of scenarios. What it is lacking though is a complete end-to-end JavaScript example. That’s why I am here today to share what I came up with.
This assumes, that you already have an id of a list item that you picked up somewhere along the way. Most likely from some other REST API call. You can put this code in an App Part or anywhere else you can make a REST call. The first part of dealing with anything with REST is constructing the URL. Again, the Basic Operations post does a great job explaining this. This all depends on where your lists is host web or app web. Let’s make an assumption that I have a list on my app web and I assign the URL to a variable spAppWebUrl it like in my previous REST post. Let’s build the rest of the URL. We use getByTitle with the list name. We then use items with an index of the list item id I mentioned earlier. Finally we need to add /AttachmentFiles to the end of the URL to get attachments.
var queryUrl = spHostUrl + "/_api/web/lists/getbytitle('MyListTitle')/items(" + id + ")/AttachmentFiles";
Here’s what it looks like together. You can paste this into a web browser window to verify it works.
Now, we need to $.ajax to make the REST call and then we’ll process the results. We’ll pass in methods to handle the success and error conditions.
$.ajax({
url: queryUrl,
accepts: {
json: "application/json;odata=verbose"
},
method: "GET",
success: onQuerySuccess,
error: onQueryError
});
In our onQuerySuccess method, we’ll iterate through the attachments and do whatever operations we need such as binding them. This will return all attachments and then we can bind it in whatever manner you like.
function onQuerySuccess(data) {
if (data) {
$.each(data.d.results, function () {
// do something
this.ServerRelativeUrl;
});
}
}
In the above example, I check to ensure the data object came back. I then loop through on data.d.results. That object will have a property ServerRelativeUrl which has a relative URL that you can use. This is great for providing a link to the document or to bind to something like an img tag.
The last thing to implement is the code to handle errors. It’s relatively simple and just writeserror.StatusText to the div.
function onQueryError(error) {
$("#resultsDiv").append(error.statusText)
}
As you can see, getting list item attachments is pretty easy using REST. Give it a try.