3

I have a SharePoint 2013 list TestList. Each record of my list has three attachments... I am trying to get the links of each attachment and display it in a table using jQuery. Is it possible?

My code:

var id;
$().SPServices({

        operation: "GetListItems",
        listName:"Test",
            webURL:"http://sharepoint.pfizer.com/sites/test/",
        CAMLViewFields: '<ViewFields><FieldRef Name=\'ID\'/></ViewFields>',
        async: false,
        completefunc: function (xData, Status) 
        {
         $(xData.responseXML).find("z\\:row, row").each(function() 
                    {
                    id=parseInt($(this).attr("ows_ID"));
ExecuteOrDelayUntilScriptLoaded(getWebProperties, "SP.js"); 
var attachmentFiles;
function getWebProperties() {
var itemId=id;
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var attachmentFolder=web.getFolderByServerRelativeUrl('Lists/Test/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("Not found!");

}
});
}
});
  • am getting an error " Unable to get property 'apply' of undefined or null reference" – Dheeraj Apr 3 '17 at 15:23
2

You can use the below REST API endpoint:

/_api/lists/getByTitle('Test')/items?$select=Title,AttachmentFiles&$expand=AttachmentFiles

The full code would be somewhat as below using REST API:

$.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getByTitle('Test')/items?$select=Title,AttachmentFiles&$expand=AttachmentFiles",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                if(data.d.results.length>0){
                    for(var i=0;i<data.d.results.length;i++)
                    {
                        var item = data.d.results[i];
                        var attachments = item.AttachmentFiles;
                        if(attachments!=null){
                            for(var j=0;j<attachments.length;j++)
                            {
                                var attachUrl = attachments[j].ServerRelativeUrl;
                                console.log(attachUrl); //this is your attachment url
                            }
                        }
                    }
                }               
            },
            error: function (data) {
                console.log(data);
            }
      });

Edited - Since you are using SPServices, you can also try below code:

var id;
$().SPServices({

        operation: "GetListItems",
        listName:"Test",
        webURL:"http://sharepoint.pfizer.com/sites/test/",
        CAMLViewFields: '<ViewFields><FieldRef Name=\'ID\'/><FieldRef Name=\'Attachments\'/></ViewFields>',
        CAMLQueryOptions: "<QueryOptions><IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls></QueryOptions>",
        async: false,
        completefunc: function (xData, Status) 
        {
         $(xData.responseXML).find("z\\:row, row").each(function() 
                {
                    id=parseInt($(this).attr("ows_ID"));
                    var attachments = [];  
                    var attCollection = $(this).attr("ows_Attachments");
                    if(attCollection !== "0") {
                        attachments = attCollection.split(";#"); // Now you'll have an array of attachment URLs
                        //iterate over this array
                        for(var j=0;j<attachments.length;j++)
                        {
                            var url = attachments[j];//untested, check the values here
                        }

                    } else {
                        // attCollection will be "0", indicating that there are no attachments
                    }

                });
        }
});

References - Get attachments using SPservices 2013

SPXmltoJSON

  • OKay...Will check and let you know – Dheeraj Apr 4 '17 at 9:10
  • 1
    But a small change...need to add Attachments in ViewFields :p – Dheeraj Apr 4 '17 at 11:35
  • Hi, this worked perfectly fine..but I am trying to pass the url dynamically in the anchor tag..And if the url has spaces or special characters..the url is breaking up.. – Dheeraj Apr 4 '17 at 12:53
  • you can try it as var url = encodeURIComponent(attachments[j]); – Gautam Sheth Apr 5 '17 at 4:44
0
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!");

}
  • Am able to retrieve only one record attachments links using this...When I dynamically tried to pass the itemId..It is throwing me an error "Unable to get property 'get_serverRelativeUrl' of undefined or null reference" – Dheeraj Apr 3 '17 at 15:04
  • Basically I want to iterate through all the records each time using SPServices each function – Dheeraj Apr 3 '17 at 15:18
0

This is the code I've used in the past to show links to all attachments for a list item - this was showing attachments on a PO page.

<div id="fmgAttach" class="fmgNoPrint"></div>
</div>
<script type="text/javascript" src="/Javascript/JQuery/JQueryMin-1.8.2.js"></script>
<script src="/Javascript/JQuery/jquery.SPServices-0.7.2.min.js"></script>
<script type="text/javascript">
var attachments = '';

// here, get the id for the list item from query parameters or other code. Change the red code to use your ID variable.


    attachments += retrieveAttachments($(this).attr("ows_ID"));

// after you've retrieve the attachments, attach the html to division

 $('#fmgAttach').append(attachments);


// ------------------------------------------------------------
// Function - Retrieve Attachments with Edit
// ------------------------------------------------------------

function retrieveAttachments(poID) {
var outputTitle = "<span class='fmgSectionH1'>Attachments for PO</span><br /><br />You can read and edit from these links. Attach via the 'Edit PO Header' button -> Attach File in the ribbon. Remember to click Save when done.<br /><br />";
var output = "";
var outputlinks = "";
 var found = false;
$().SPServices({
  operation: "GetAttachmentCollection",
  listName: "Purchase Orders",
  ID: poID,
  async: false,
  completefunc: function( xData, Status ) {

   $( xData.responseXML ).find("Attachments > Attachment").each(function( i, el ) {
   found = true;
    var $node = $(this),
     filePath = $node.text(),
     arrString = filePath.split("/"),
     fileName = arrString[ arrString.length - 1 ]
    ;
      outputlinks += "<a href='" + filePath + "' target='_blank' onclick=\"DispDocItemExWithServerRedirect(this, event, 'FALSE', 'FALSE', 'FALSE', 'SharePoint.OpenDocuments.3', '1', '');return false;\" >"; 
    outputlinks += fileName;
    outputlinks += "</a><br /><br />";

   });

  }
 });


 return (outputTitle + "<table width='100%'><tr><td>" + outputlinks + "</td><td>" + output + "</td></tr></table>");
}
</script>

<style>



/* attachments */
.fmgSectionH1 {

  font-weight: bold;
}
#fmgAttach {
 border: 1px solid black;
 padding: 10px;
}

</style>

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.