The requirement is as follows:
1. We have a SP list. All items in the list have mulitple attachments.
2. On click of a button, All the attachments of all items should be copied to a document library
This is to be done from client side only. No server code is acceptable. We have tried following things:
1. USing Asynch call
context = new SP.ClientContext(“my site name”);
this.oWebsite = context.get_web();
var lists = oWebsite.get_lists();
var list = lists.getByTitle(‘my list name’);
context.load(oWebsite);
var folderPath = ‘Lists/<my list name>/Attachments/’ + folderId;
var Folder = oWebsite.getFolderByServerRelativeUrl(folderPath);
context.load(Folder);
Files = Folder.get_files();
context.load(Files);
context.executeQueryAsync(Function.createDelegate(this, this.ExecuteCopyOnSuccess), Function.createDelegate(this, this.ExecuteCopyOnFailure));
function ExecuteCopyOnSuccess(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 = ‘document library url’;
file.copyTo(newUrl, true);
context.executeQueryAsync(null,null);
}
}
}
In this case, Files.get_count() throws error – The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
2. Using copy.asmx service
It copies files to document library but some files are blank and are having size 0.
Any pointers for above issue ..
Thanks in Advance …!
This is working code for you..
<script language=”javascript” type=”text/javascript”>
var Files;var myContext;
function CopyAtt(ItemID) {
try {
myContext = new SP.ClientContext.get_current();
var myWeb = myContext.get_site().get_rootWeb();
var myList = myWeb.get_lists().getByTitle(‘ToDelete’);
var folderPath = ‘Lists/<list name>/Attachments/’ + ItemID;
var Folder = myWeb.getFolderByServerRelativeUrl(folderPath);
Files = Folder.get_files();
myContext.load(Files);
myContext.executeQueryAsync(Function.createDelegate(
this, ExecuteCopyOnSuccess),
Function.createDelegate(
this, GetLeadsFail));
}
catch (err) {
alert(err.Line);
}
}
function GetLeadsFail(sender, args) {
// Show error message
alert(‘GetLeadsFail() failed:’ + args.get_message());
}
function ExecuteCopyOnSuccess(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 = ‘/<list name>/’ + filename;
file.copyTo(newUrl, true);
myContext.executeQueryAsync(null, null);
}
}
</script>
