Search code examples
javascriptrestsharepointsharepoint-2013sharepoint-jsom

How to get attachment document into form or download it to local from sharepoint List


I have a list in sharepoint 2013 and created an html form and script which will insert data and upload a document into this list. Now for second level, i want to fetch and only view all these saved data which i created. I used jsom to fetch all the records

But problem is with attachment- How to get attachment document into form or download it to local from this list. Not finding any good resource in google. Can any one please help me?.


Solution

  • You could use JSOM to get the attachement files.

    Sample script:

    <script type="text/javascript" src="/SiteAssets/jquery-3.4.1.js"></script>
        <script type="text/javascript">
            function getListItemAttachements() {
                //replace the list and id dynamically
                getAttachements("Test", 1);
            }
            function getAttachements(listName, itemID) {
                var attachmentFiles;
                var ctx = new SP.ClientContext.get_current();
                var web = ctx.get_web();
                var attachmentFolder = web.getFolderByServerRelativeUrl('Lists/' + listName + '/Attachments/' + itemID);
                attachmentFiles = attachmentFolder.get_files();
                ctx.load(attachmentFiles);
                ctx.executeQueryAsync(function () {
                    for (var j = 0; j < attachmentFiles["$2_1"].length; j++) {
                        var file = attachmentFiles.itemAt(j);
                        console.log(file.get_name());
                    }
    
                }, function (err) {
                    console.log(err);
                });
            }
        </script>
        <input id="Button1" onclick="getListItemAttachements()" type="button" value="button" />