This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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