我有一个列表,每行最多有1个附件,我正在尝试将每个附件从此列表复制到新创建的图片库。
我可以通过以下代码复制1个附件,
var Files;
var myContext;
function CopyAtt(ItemID) {
try {
myContext = new SP.ClientContext.get_current();
var myWeb = myContext.get_site().get_rootWeb();
var folderPath = 'Lists/test/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 = 'PictureLibrary/' + filename;
file.copyTo(newUrl, true);
myContext.executeQueryAsync(null, null);
}
}
$(document).ready(function() {
CopyAtt(3);
}
当我尝试从
CopyAtt(ItemID)
多次调用$(document).ready
时,代码在控制台中显示错误。
Uncaught TypeError: Cannot read property 'collectionHasNotBeenInitialized' of undefined
Uncaught RangeError: Maximum call stack size exceeded
我怀疑它与文件有关,但找不到任何线索,有人可以给我一些建议吗?
最佳答案
几天后我得到了解决方案,问题与文件无关,但与myContext.executeQueryAsync(null, null);
有关。
首先,我多次拨打CopyAtt(ItemID)
for (i=0; i< Items.Length; i++){
CopyAtt(Items[i]);
}
executeQueryAsync()
中的CopyAtt(ItemID)
将打破循环并显示上面的错误。递归可以避免此类错误,而不是for循环,并且每个
executeQueryAsync()
将仅在一个完成后执行。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);
}