I have to create a sharepoint hosted app (Office 365) for copying a latest version of a file from one site collection to another site collection under the same tenant, using JSOM. Can someone direct me to the right solution?

  • You need to first perform read operation and then create operation. Please follow this link – nbi Oct 1 '15 at 6:11

Courtesy MSDN

function readFile(sourceSiteUrl,targetSiteUrl) {
    var clientContext;
    var oWebsite;
    var fileUrl;

    clientContext = new SP.ClientContext.get_current();
    oWebsite = new SP.AppContextSite(clientContext, sourceSiteUrl).get_web();

    clientContext.executeQueryAsync(function () {
        fileUrl = oWebsite.get_serverRelativeUrl() +
            "/Lists/Shared Documents/TextFile1.txt";
            url: fileUrl,
            type: "GET"
            .done(Function.createDelegate(this, successHandler))
            .error(Function.createDelegate(this, errorHandler));
    }, errorHandler);

    function successHandler(data) {

    function errorHandler() {
        alert("Request failed: " + arguments[2]);

function createFile(data,targetSiteUrl) {
    var clientContext;
    var oWebsite;
    var oList;
    var fileCreateInfo;
    var fileContent;

    clientContext = new SP.ClientContext.get_current();
    oWebsite = new SP.AppContextSite(clientContext, targetSiteUrl).get_web();
    oList = oWebsite.get_lists().getByTitle("Shared Documents");

    fileCreateInfo = new SP.FileCreationInformation();
    fileCreateInfo.set_url("my new file.txt");
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    fileContent = data;

    for (var i = 0; i < fileContent.length; i++) {


    this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);

        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)

    function successHandler() {

    function errorHandler() {
        alert("Request failed: " + arguments[1].get_message());

readFile('url of source site','url of target site');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.