7

How can I fetch the attachments (the URL, to be precise) of a list item with SPServices (the jQuery library)?

9

How to retrieve attachment files using SPServices

function getAttachmentFiles(listName,listItemId,complete) 
{
   $().SPServices({
        operation: "GetAttachmentCollection",
        async: false,
        listName: listName,
        ID: listItemId,
        completefunc: function(xData, Status) {
            var attachmentFileUrls = [];    
            $(xData.responseXML).find("Attachment").each(function() {
               var url = $(this).text();
               attachmentFileUrls.push(url);
            });
            complete(attachmentFileUrls);
        }
   });
}

Usage

getAttachmentFiles('Requests',1,printAttachments);

function printAttachments(urls){
    for(var i =0; i< urls.length; i++){
        console.log(urls[i]);     
    };    
}
  • Just a heads up to sleepy people like me, don't forget to change the listName and ID to your list and the item ID which has the image on the func. Else you'll get a _vti_bin/Lists.asmx 500 (Internal Server Error) error in the console) – Mint Jul 14 '15 at 23:55
1

This should get you where you need to go:

ExecuteOrDelayUntilScriptLoaded(getWebProperties, "SP.js");            
var attachmentFiles;

function getWebProperties() {
    var itemId=2;
    var ctx = new SP.ClientContext.get_current();
    var web = ctx.get_web();
    var attachmentFolder=web.getFolderByServerRelativeUrl('Lists/City/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("sorry!");
}
0

I just wanted to amend an alternate formation of the onSuccess function that worked better for me:

function onSuccess(sender, args) {                                      
    var i = 0;
    while (attachmentFiles.itemAt(i)) {
        var file = attachmentFiles.itemAt(i).get_serverRelativeUrl();
        alert(file);
        i++;
    }
}

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.