Get list item attachments with ECMASCRIPT\JavaScript Client object model SharePoint 2010

This is another blog post in the . In this example we will see how to retrieve all the attachments from a list item with ECMASCRIPT\JavaScript Client object model SharePoint.

Each file that is attached with a list item is saved in a ItemID folder. You can access attachments using

Path -> “/Lists/RootFolder/listname/itemId”

To get the files using ECMAScript\JavaScript Client OM you can use the code below

<script type=”text/javascript”>

  ExecuteOrDelayUntilScriptLoaded(getAttachments, “SP.js”);

  var attachmentFiles;

function getAttachments() {

var itemId=2;

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.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(“No Files attached”);

    }

</script>

Related Posts

  • Ryan

    Thanks for post Isha.
    Is there a way to Upload a file to a custom list using ecmascript/javascript? I’d prefer to use REST via ajax but so far have had no success. Now looking into the COM as an option.

    Thanks