6

I have a file in a document library called images: https://xxx.sharepoint.com/Site1/Images

... and I would like to copy the file to the document library called backup in this site:

https://xxx.sharepoint.com/Site2/Backup

I would like to do this by using javascript and REST API. I have looked at this referance for the REST API: http://msdn.microsoft.com/en-us/library/office/dn450841(v=office.15).aspx#bk_FileCopyTo

I get the following error (translated, might not be exact): "There is no appcontext to perform the request"

My javascript looks like this:

function copy() {
    var executor = new SP.RequestExecutor('https://xxx.sharepoint.com/Site1/MyImages/');
    var url = "https://xxx.sharepoint.com/Site2/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/Site1/Images/1.jpg')/" +
        "/copyto(strnewurl='/Site2/Backup/1.jpg',boverwrite=false)" +
        "?@target='https://xxx.sharepoint.com/Site2/Backup/'";
    executor.executeAsync({
        url: url,
        method: "GET",
        success: successHandler,
        error: errorHandler
    });

    function successHandler() {
        console.log('success');
    };

    function errorHandler() {
        console.log('fail');
    };
}
1
  • Unfortunately, as Vadim correctly mentioned, CopyTo is only applicable within a Site (SPWeb), not within a SiteCollection.
    – A Ismaili
    Dec 4, 2017 at 16:56

2 Answers 2

11

Using SP.File.copyTo Method in REST endpoint, it is supported to copy files within a site only, for example:

executor.executeAsync({
  url: "<app web url>/_api/SP.AppContextSite(@target)/web
    /getfilebyserverrelativeurl('/Shared Documents/filename.docx')
    /copyto(strnewurl='/foldername/filename.docx',boverwrite=false)
    ?@target='<host web url>'",
  method: "POST",
  success: successHandler,
  error: errorHandler
});

where source file (/Shared Documents/filename.docx) and destination file (/foldername/filename.docx) are supposed to be located on the same site

Note: POST method is used for a CopyTo operation

To copy files between sites using JavaScript REST in Office 365 / SharePoint 2013, please follow an article How to copy files between sites using JavaScript REST in Office365 / SharePoint 2013.

0
2

Change source url and destination url before executing. On click on move button initListName() method can be called. Once SP.RequestExecutor.js is loaded Copy function can be done. This code can be used to copy files across site collection.

If copy is within site collection Function CopyTo can be directly used.

     var hostweburl="https://xxx.sharepoint.com";//edit

        function initListName() { 
          var scriptbase = hostweburl + "/_layouts/15/"; 
          $.getScript(scriptbase + "/SP.RequestExecutor.js", copyFile);
        }

        function copyFile() { 
          var sourceUrl=sourceUrlParam;//provide source site url
          var destUrl=destinatonUrlParam;//provide destination site url 
          // Create a request executor.
          var sourceExecutor = new  SP.RequestExecutor(sourceUrl); 
          var targetExecutor = new SP.RequestExecutor(destUrl); 
          var fileName="/sites/TestDemo/ProjectAttachments/Test%20123.docx";
         //provide file name with path 
       var fileContentUrl=sourceUrl+"/_api/web/GetFileByServerRelativeUrl('"+fileName+"')/$value";

        var targetSiteUrl=destUrl;

        //var folderName='ProjectAttachments';

        var newFileName="Test123.docx";//New name of added file
        var folderName="/sites/TestDemo/ProjectAttachments";
//provide folder path to which file to be copied
        var restUrl=targetSiteUrl+"/_api/web/GetFolderByServerRelativeUrl('"+folderName+"')/Files/Add(url='"+newFileName+"',overwrite=true)";

        $.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: fileContentUrl,
                    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: restUrl,
                            method: "POST",
                            headers: {
                                "Accept": "application/json; odata=verbose",
                                "X-RequestDigest": digest
                            },
                            contentType: "application/json;odata=verbose",
                            binaryStringRequestBody: true,
                            body: getFileData.body,
                            success: function(copyFileData) {
                            alert("successfully Copied");
                            },
                            error: function(ex) {
                            alert("Something went wrong, please try again later");
                                //show your 'failed' message
                            }
                        };

                        targetExecutor.executeAsync(copyFileAction);
                    },
                    error: function(ex) {
                        //fail
                        alert("Something went wrong, please try again later");
                    }
                };
                sourceExecutor.executeAsync(getFileAction);
            },
            error: function(ex) {
                //fail
                alert("Something went wrong, please try again later");
            }
        });
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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