JS Code To Copy Folders And Files From One Library To Another On The Same SubSite
-
01-01-2021 - |
Domanda
Trying to find a way to copy folders(with documents inside) and files from a SharePoint Online Library to another, need to preserve the metadata of the files as well. The new modernized experience on SharePoint has a built in feature to do that, but I have a classic experience site that has that feature restricted, so need to find a way to do it there, ideally triggered from a button in the ribbon. Any help will be very much appreciated!
Soluzione
Found a solution for selected multiple files in a library to be copied to another library in the same sub-site, here is the tested and working code, it is for selected files only, the syntax for folders will be similar, the SP.MoveCopyUtil.copyFile will become SP.MoveCopyUtil.copyFolder:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<input type="button" value="Copy Files" style="cursor:pointer;" onclick="copyFiles()" />
<script type="text/javascript">
function copyFiles()
{
var context = SP.ClientContext.get_current();
var selectedItemIds = SP.ListOperation.Selection.getSelectedItems(context);
var output = "Destination Library";
for (idx in selectedItemIds)
{
SP.MoveCopyUtil.copyFile(context, $("#" + selectedItemIds[idx].id + " a")[0].href.toString(), output + $("#" + selectedItemIds[idx].id + " a")[0].href.split("/")[$("#" + selectedItemIds[idx].id + " a")[0].href.split("/").length - 1].toString(), true );
}
context.executeQueryAsync(function(){alert("OK")}, function(){alert("NOT OK")});
}
</script>
Altri suggerimenti
After update 2
I tested it in my SPO and its working correctly.
Assumptions:
- List view webpart
- File name is present in the list view webpart
<script>
function copyFiles() {
var current_context = SP.ClientContext.get_current();
var web = current_context.get_web();
var selectedItems = SP.ListOperation.Selection.getSelectedItems();
for (var i = 0; i < selectedItems.length; i++) {
var id = selectedItems[i].id;
debugger;
var element = document.getElementById(id).children[0];
var filePath = "";
var fileName = "";
if (element) {
debugger;
filePath = element.href;
fileName = element.href.split('/').pop();
var output = "https://mySiteUrl.sharepoint.com/DocumentLibrary/" + fileName;
SP.MoveCopyUtil.copyFile(current_context, filePath, output, true);
current_context.executeQueryAsync(function () {
PageCopySuccess(); }, function () { PageCopyFailure();
});
function PageCopySuccess() {
alert('Success');
}
function PageCopyFailure() {
debugger;
console.log(arguments);
alert('Failed');
}
}
}
}
</script>
<input type="button" value="Copy Files" style="cursor:pointer;" onclick="copyFiles()" />