An easy way to copy or move files with JavaScript between SharePoint libraries within the same site is using the methods copyTo and moveTo from the SP.File class.
Both functions receive the same first parameter, which is the future URL of the document to be moved/copied, but the second parameter is different.
In the case of the moveTo function, it expects an enum value of type SP.MoveOperations. This parameter determines the kind of operation to execute when copying the file.
1 | SP.File.moveTo(newUrl, flags); |
The options available for the flag value are:
- SP.MoveOperations.none
- SP.MoveOperations.overwrite
- SP.MoveOperations.allowBrokenThickets
- SP.MoveOperations.bypassApprovePermission
The copyTo function expects a bool value that simply indicates whether the file should be overwritten or not in case the file already exist in the destination library.
1 | SP.File.copyTo(strNewUrl, bOverWrite); |
If the file already exist in the destination library and the bOverWrite value is false, an error will occur while executing the instruction. The same will happen with the moveTo function when the _SP.MoveOperations.none _enum is passed as the flag parameter.
Here is a simple function that takes the parameters needed to copy or move a file.
I’ve tested this code in SharePoint 2010, SharePoint 2013 and SharePoint Online as well.
Hope you like it and find it useful.