2

I am trying to write custom code for list item attachments. As it is not allowed to overwrite them, I will check if file already exists. If yes, will delete and then upload again.

I found a method SP.AttachmentCollection.getByFileName Method (sp.js) which can fetch list item by file name. Does anyone has sample code for this?

I am not able to find any documentation on this.

1

You can simply invoke a REST call to following URL

/_api/lists/getByTitle('ListTitle')/getItemById(1)/AttachmentFiles/getByFileName('filename')

Then check the response to see if file exists or not.

JSOM

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

        //Attachment exists and no need to re attach
    }       
}

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

var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle("ListTitle");
var listItem = list.getItemById(1);
clientContext.load(listItem);
clientContext.load(listItem.get_attachmentFiles().getByFileName("FileName"));
clientContext.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFailure));
  • Thanks for your answer but I am looking for JSOM code. – Garima Mar 25 '15 at 11:58
  • Ok. But you can still invoke a REST call from JSOM which will be easier. I will look around and see any JSOM sample is available. – Amal Hashim Mar 25 '15 at 11:59
  • @Garima I have added JSOM sample. – Amal Hashim Mar 25 '15 at 12:25
  • Thanks Amal. really helpful. I will try this and will let you know. – Garima Mar 25 '15 at 12:33
  • Once you've gotten the attachment, how can you use that to retrieve its binary? It looks like this simply shows binary info. If I perform a regular "GET" on the filepath itself, this doesn't seem to return the binary properly for most file types.. – Dinerdo Sep 10 '15 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.