2

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
0

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.load(oWebsite);
    clientContext.executeQueryAsync(function () {
        fileUrl = oWebsite.get_serverRelativeUrl() +
            "/Lists/Shared Documents/TextFile1.txt";
        $.ajax({
            url: fileUrl,
            type: "GET"
        })
            .done(Function.createDelegate(this, successHandler))
            .error(Function.createDelegate(this, errorHandler));
    }, errorHandler);

    function successHandler(data) {
        createFile(data,targetSiteUrl);
    }

    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++) {

        fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
    }

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

    clientContext.load(this.newFile);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );

    function successHandler() {
       //success
    }

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

//calling
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.