Thursday, 31 July 2014

SharePoint read list item attachments


function ReadList(listName, id, onSuccess) {
var odata = [];
//var listName = "MyList";
//var id = "20";
var objcontext = new SP.ClientContext();
var web = objcontext.get_web();
var attachmentFolder = web.getFolderByServerRelativeUrl('Lists/' + listName + '/Attachments/' + id);
var attachmentFiles = attachmentFolder.get_files();
objcontext.load(attachmentFiles);
objcontext.executeQueryAsync(function () {
var cnt = attachmentFiles.get_count();
if (cnt > 0) {
var AttachArray = [];
for (var i = 0; i < cnt; i++) {
var fileName = attachmentFiles.itemAt(i).get_name();
AttachArray.push({ "FileName": fileName, "FileURL": attachmentFiles.itemAt(i).get_serverRelativeUrl() });
}
odata.push({ "Title": objItem.get_item('Title'), "AllAttachments": AttachArray });
onSuccess(odata);
}
else {
odata.push({ "Title": objItem.get_item('Title') });
onSuccess(odata);
}
}, function () {
console.log("Failed.Error:" + args.get_message());
});
}
//How to call above function, in UI
$(document).ready(function () {
ReadList("MyList", "20", function (odata) {
alert(odata[0].Title);
if (odata[0].AllAttachments) {
$.each(odata[0].AllAttachments, function (key, value) {
alert(value.FileName);
alert(value.FileURL);
});
}
});
});
view raw gistfile1.js hosted with ❤ by GitHub