How to load attachment in client context?

231 Views Asked by At

I have a list with attachments. I want to fetch list records with attachment as a url in anchor tag. For ex- when user selects ID-100 then all its data will be retrieved and attachment in anchor tag to open it. I used JSOM for this and it is working fine but it is giving error when there is no documents attached. Please help-

       var clientContext = new SP.ClientContext.get_current();
       var oList=clientContext.get_web().get_lists().getByTitle(varListName);
         var camlQuery = new SP.CamlQuery();
        //var camlQuery = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>1</Value></Eq></Where></Query></View>";
        camlQuery.set_viewXml("<View><Query><Where>" +
        "<Eq><FieldRef Name=\"ID\"/><Value Type=\"Number\">" + varid + "</Value></Eq>" +
        "</where><OrderBy></OrderBy></Query><RowLimit>1</RowLimit></View>");

            this.collListItem = oList.getItems(camlQuery);
            var attachmentFolder = clientContext.get_web().getFolderByServerRelativeUrl('Lists/' + varListName + '/Attachments/' + varid);
         
            this.attachmentFiles = attachmentFolder.get_files();
            clientContext.load(collListItem);
            
            clientContext.load(attachmentFiles);
            
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        

}

1

There are 1 best solutions below

0
On

We can first check if the item has attachment or not via ListItem.Attachments property.

In case if list List Item contains attachments, submit a second request to retrieve attachment files.

this.collListItem = oList.getItems(camlQuery);
var listItemEnumerator = collListItem.getEnumerator();

// on query success
while (listItemEnumerator.moveNext()) {
       var oListItem = listItemEnumerator.get_current();
       var hasAttachments = item.get_fieldValues()['Attachments'];
          
       //  getAttachmentFiles ....
}

BR