Skip to content
Amal Hashim
All posts
Snippet

SharePoint - JSOM Sample for SP.AttachmentCollection.getByFileName Method

A JavaScript client object model sample that fetches a list item attachment by file name.

1 min read#JavaScript#SharePoint 2013

A question on SharePoint StackExchange asked how to use getByFileName with the Client Side Object Model. The method is not documented with a sample in the MSDN reference, so here is one.

Change LISTNAME, ID and FILENAME to your own values.

js
var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle("LISTNAME");
var listItem = list.getItemById(ID);
clientContext.load(listItem);
clientContext.load(listItem.get_attachmentFiles().getByFileName("FILENAME"));
clientContext.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFailure));

function onSuccess(sender, args) {
	var item = listItem;
	var total = item.get_attachmentFiles().get_count();
	if (total > 0) {
		console.log(total + " file attachments");
	}
}

function onFailure(sender, args) {
	// request failed
}