2

I have a site collection MySiteCollection which contains many subsites like SiteA, SiteB, SiteC, etc. Each subsite contains its own subsites. For example SiteA-1, SiteA-2, SiteA-3.

And I want to copy a document from a library in the root site of MySiteCollection to a subsite like SiteA-3 with REST API.

I found some examples, but they don't work for me. So if you have a solution for this problem, I would be glad if you can post it.

sketch

4

SharePoint REST API contains SP.File.copyTo Method:

Endpoint URI

http://<sitecollection>/<site>/_api/web/folders/getbyurl(folderrelativeurl)/files/getbyurl(filerelativeurl)/copyTo(strNewUrl,bOverWrite)

for copying the file to the destination URL , but it is supported to copy files within a same site only, for example:

function copyTo(sourceFileUrl,targetFileUrl, success,error)
{
    var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfilebyserverrelativeurl('" + sourceFileUrl + "')/copyto(strnewurl='" + targetFileUrl + "',boverwrite=false)"; 
    return $.ajax({
            url: endpointUrl,
            method: "POST",
            contentType: "application/json;odata=verbose",
            headers: {   
             "Accept": "application/json;odata=verbose",
             "X-RequestDigest": $("#__REQUESTDIGEST").val()
            }, 
        });
}    

Usage

copyTo('/site/Documents/SharePoint User Guide.docx','Documents/SharePoint User Guide 2013.docx')
   .done(function(data){
       console.log('File has been copied successfully');    
   })
   .fail(function(error){
       console.log(JSON.stringify(error));
   }); 

To copy files between sites using REST API you could consider the following approach:

  • retrieve a source file content using /web/GetFileByServerRelativeUrl('<sourcefileurl>')/$value endpoint
  • upload a file to target location using /_api/web/GetFolderByServerRelativeUrl('<targetfolderurl>')/Files/Add(url='filename',overwrite=true) endpoint

Follow an article How to copy files between sites using JavaScript REST in Office365 / SharePoint 2013 for a complete solution.

| improve this answer | |
  • +1, {@Vadim}, how can one get around the issue of having long urls in case of SP.File.copyTo Method.? – Nadeem Yousuf-AIS Mar 16 '15 at 4:19
  • Regarding the issue of having long url, one option to shorten endpoint url would be to specify site relative url for copyTo method (see the 'Usage' section in the updated answer) – Vadim Gremyachev Mar 16 '15 at 9:43
  • {@Vadim}, is there any way of specifying this in the request body? I ask this because I believe CopyTo can be used to copy files to sub sites in the same site. What if there are many levels of nested sub sites and url passes the 256 character limit. – Nadeem Yousuf-AIS Mar 16 '15 at 9:55
  • Thanks @VadimGremyachev ! I was struggling a lot with this, now I used your code and it finally works! By the way, is it possible to get back the ID of the new copied document? – Gintas K Apr 13 '16 at 9:33
  • @NadeemYousuf, did you find any solution for 256 character limit? i m facing same issue – Anil D Nov 22 '16 at 3:34
0

I finally found a solution which copy the document for me.


$.ajax({
            url: currentSiteUrl + "/_api/web/getfilebyserverrelativeurl('" + sourceFileRef + "')/$value",
            type: "GET",
            headers: { "Accept": "application/json;odata=verbose" },
            binaryStringResponseBody: true
        }).done(function (result) {
            if (result=== null) {
                console.error("Data is null");
                dfd.reject();
            }
            else {
                $.ajax({
                    url: targetUrl + "/_api/web/getfolderbyserverrelativeurl('" + targetFileRef + "')/files/add(url='" + newFileName + "')",
                    method: "POST",
                    headers: {
                        "Accept": "application/json;odata=verbose",
                        "X-RequestDigest": _REQUESTDIGEST
                    },
                    contentType: "application/json;odata=verbose",
                    binaryStringRequestBody: true,
                    data: result,
                }).done(function (data) {
                    console.log("Document copied.");

                }).fail(function (data) {
                    console.error("Document copy failed.");
                    console.log(data);
                    console.trace();
                });
            }
        }).fail(function (data) {
            console.error("Document can not be found.");
            console.log(data);
            console.trace();
        });

Now I have a new problem. My copied document is empty. So what can I do?

| improve this answer | |
0

Have been struggling with this a few times

  1. CopyTo only works within a site and removes all version history.
  2. Using Rest and downloading the content as binary data crashes the browser for files larger than 40 MB.

SPServices! This oldie using Copy.asmx seems to work (also in SP Online) to copy files between different sites and with large files: http://spservices.codeplex.com/wikipage?title=CopyIntoItemsLocal&referringTitle=Copy

| improve this answer | |

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.