Get Attachment URL from list item (en)


Get Attachment URL from list item en Title
, , ,

afraIT Shorty-Time! Just want to share a little script on how to get the attachment url or the attachment filename of an list item in SharePoint 2013.

There is often the request, that someone wants to get the complete URL of an uploaded document, picture or whatever.

Here it is, a short javascript with a little REST in it:

<script type="text/javascript">
	
    $(document).ready(function() {
       	
		// Rest URL
		var requestUri = "/_api/lists/getbytitle('Marketplace')/items?$select=Title,ID,Attachments,AttachmentFiles&$expand=AttachmentFiles";
					
            $.ajax({
                url: requestUri,
                type: "GET",
                headers: { "ACCEPT": "application/json;odata=verbose" },
                success: function (data) {
                    
					$.each(data.d.results, function (i, item){
                       	var title = item.Title;
                       	var id = item.ID;
						var attachmentUrl = item.AttachmentFiles.results[0];
																	
						//alert(attachmentUrl.FileName);
						//alert(attachmentUrl.ServerRelativeUrl);
																	
                    })
                },
                error: function () {
                    alert("Error getting the Marketplace Items");
                }                     
            });
      });      

</script>

The script is pretty easy. The big point here is the requestUri. You have to select the Attachments and the AttachmentFiles. After that you can append the expand and select the AttachmentFiles.

Then you can show either the FilesName or the URL. You can see the alert’s which are commented out in line 19 and 20.

Hope this can help you a little bit. If you like the Shorty-Section, click here to get more of those and if you like it, share it or follow me on twitter or facebook.

3 responses to “Get Attachment URL from list item (en)”

  1. Hi, this works but the $.each only iterates once with my test that should return 3 attachments. Can you help?

  2. Nevermind. I figured it out. I had to add a while loop around ‘var attachmentUrl’. Thanks for the example!

Leave a Reply

Your email address will not be published. Required fields are marked *