Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

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]);     
    };    
}
share|improve this answer
    
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 at 23:55

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!");
}
share|improve this answer

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++;
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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