Skip to content

Instantly share code, notes, and snippets.

@lesagesander
Created July 3, 2014 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lesagesander/e2ce1a87fad09893e468 to your computer and use it in GitHub Desktop.
Save lesagesander/e2ce1a87fad09893e468 to your computer and use it in GitHub Desktop.
function copyFile(targetSiteUrl, contextId, targetFileName, targetList) {
//get current search result item
var currentItem = window.ctxData[contextId];
// Create a request executor.
var sourceExecutor = new SP.RequestExecutor(currentItem.SPSiteUrl);
var targetExecutor = new SP.RequestExecutor(targetSiteUrl);
// Get the absolute server url.
var serverUrlRegex = new RegExp(/http(s?):\/\/([\w]+\.){1}([\w]+\.?)+/);
var serverUrl = serverUrlRegex.exec(currentItem.SPSiteUrl)[0];
// Get the source file url.
var fileUrl = currentItem.Path.substr(serverUrl.length, currentItem.Path.length - serverUrl.length);
// Get the target folder url.
var folderUrl = targetSiteUrl.substr(serverUrl.length, targetSiteUrl.length - serverUrl.length) + "/" + targetList;
// Get form digest of target site collection
$.ajax({
url: targetSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (data) {
var digest = data.d.GetContextWebInformation.FormDigestValue;
// Build executor action to retrieve the file data.
var getFileAction = {
url: currentItem.SPSiteUrl + "/_api/web/GetFileByServerRelativeUrl('" + fileUrl + "')/$value",
method: "GET",
binaryStringResponseBody: true,
success: function (getFileData) {
// Get the binary data.
var result = data.body;
// Build executor action to copy the file data to the new location.
var copyFileAction = {
url: targetSiteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files/Add(url='" + targetFileName + "." + currentItem.FileExtension + "', overwrite=true)",
method: "POST",
headers: {
"Accept": "application/json; odata=verbose",
"X-RequestDigest": digest
},
contentType: "application/json;odata=verbose",
binaryStringRequestBody: true,
body: getFileData.body,
success: function(copyFileData) {
//show your 'file copied successfully' message
},
error: function(ex) {
//show your 'failed' message
}
};
targetExecutor.executeAsync(copyFileAction);
},
error: function(ex) {
//fail
}
};
sourceExecutor.executeAsync(getFileAction);
},
error: function(ex) {
//fail
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment