Search This Blog

Tuesday, March 1, 2016

SharePoint 2013 working with file: How to get attachments of SharePoint list item using REST services

In previous few articles we saw how to work with files and folders in the documents library using SharePoint 2013 REST services. Now lets see how to work with attachments of list items using SharePoint 2013 REST services. They are also important part of the SharePoint list. So SharePoint has given necessary APIs to interact with attachments. In this article we will see how to get attachments of list item.

Following is the REST URL to get all attachments:

/_api/web/lists/getbytitle([List Title])/items(1)/AttachmentFiles/
In response you will get all details of file as well as the URL of file.

Following is the sample code snippet to get all attachments:

<html>
<head>
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<script src="/Site%20Assets/js/jquery-1.11.1.min.js"></script>
<script>
function GetAllAttachments()
{
                $.ajax(
                {
                url: "/_api/web/lists/getbytitle('testlist')/items(1)/AttachmentFiles/",  
                method: "GET",
                headers: {
                                "ACCEPT": "application/json;odata=verbose",
                                "content-type": "application/json;odata=verbose"                         
                },
                success: function (data) {
                                var htmlStr = "";
                                $.each(data.d.results, function(){
                               
                                                if(htmlStr === "")
                                                {
                                                                htmlStr = "<li 'ServerRelativeUrl="+ this.ServerRelativeUrl + "'>"  + this.FileName + "</li>";
                                                }
                                                else
                                                {
                                                                htmlStr = htmlStr + "<li 'ServerRelativeUrl="+ this.ServerRelativeUrl + "'>"  + this.FileName + "</li>";
                                                }
                               
                                });
                               
                                $("#foldersDiv").html(htmlStr);
                },
                error: function (data) {
                                alert("Error occured." + data);
                }
});          
                                               
}

</script>

</head>
<body>
<div>
                <input type="submit" onclick="GetAllAttachments()" value="Get All Attachments"> </input>
</div>

<div>
                <ul id="foldersDiv">
                </ul>
               
</div>
</body>
</html>


No comments:

Post a Comment