Reputation: 11
How to copy the list attachment to document library using CSOM.
Upvotes: 0
Views: 413
Reputation: 1889
@ALI RAZA ZAFAR,
Please take a reference of below csom code:
context.Load(context.Web, x => x.ServerRelativeUrl);
context.ExecuteQuery();
Console.WriteLine($"web url:{context.Web.ServerRelativeUrl}");
List targetList = context.Web.Lists.GetByTitle("myanno");
ListItem oItem = targetList.GetItemById(3);
context.Load(targetList);
context.Load(oItem);
context.ExecuteQuery();
Attachment oAttachment = oItem.AttachmentFiles.GetByFileName("custom.txt");
context.Load(oAttachment);
context.ExecuteQuery();
Console.WriteLine(oAttachment.ServerRelativeUrl);
File attachfile = context.Web.GetFileByServerRelativeUrl(oAttachment.ServerRelativeUrl);
attachfile.CopyTo(context.Web.ServerRelativeUrl + "/mytestdoclib/test/customcopy.txt", true);
context.Load(attachfile);
context.ExecuteQuery();
Upvotes: 1
Reputation: 117
Please use this script. Add Items Id's to be copied in Items Array as [id1,id2] and rename your library name used as "PictureLibrary" and replace folderPath list name used as "test"
function CopyAtt(Items, itemIndex) {
try {
myContext = new SP.ClientContext.get_current();
var myWeb = myContext.get_site().get_rootWeb();
var folderPath = 'Lists/test/Attachments/' + Items[itemIndex];
var Folder = myWeb.getFolderByServerRelativeUrl(folderPath);
Files = Folder.get_files();
myContext.load(Files);
myContext.executeQueryAsync(Function.createDelegate(
this, ExecuteLoadFileSuccess(Items, itemIndex);),
Function.createDelegate(
this, GetLeadsFail));
}
catch (err) {
alert(err.Line);
}
}
function GetLeadsFail(sender, args) {
// Show error message
alert('Request failed - ' + args.get_message());
}
function ExecuteLoadFileSuccess(Items, itemIndex, sender, args) {
for (var p = 0; p < this.Files.get_count(); p++) {
var file = Files.itemAt(p);
var filename = file.get_name();
}
if (filename != null) {
var newUrl = 'PictureLibrary/' + filename;
file.copyTo(newUrl, true);
myContext.executeQueryAsync(Function.createDelegate(
this, function(){ExecuteCopyOnSuccess(Items, itemIndex);}),
Function.createDelegate(
this, GetLeadsFail));
}
}
function ExecuteCopyOnSuccess(Items, itemIndex, sender, args) {
//Call CopyAtt() after copy files success.
if (itemIndex <Items.length-1) {
CopyAtt(Items, itemIndex+1);
}
}
$(document).ready(function() {
//save all Items ID in an array.
var Items = [2,3,6,7,8,10];
CopyAtt(Items, 0);
}
Upvotes: 1