1

I need to copy a file from one SharePoint online site document library to another SharePoint online document library under the same tenant.

I have used "sp-pnp-js": "^3.0.10" in my solution.

Below is my code snippet,

// let sourceFIleUrl = "https://mytentant.sharepoint.com/contoso1/Shared Documents/folder1/new-file.docx";
// let destinationFileUrl = "https://mytentant.sharepoint.com/contoso2/Shared Documents/folder2/new-file.docx";
    
// I have tried adding server relative url like below
    
let sourceFIleUrl = "/contoso1/Shared Documents/folder1/new-file.docx";
let destinationFileUrl = "/contoso2/Shared Documents/folder2/new-file.docx";
        
sp.web.getFileByServerRelativePath(sourceFIleUrl).copyTo(destinationFileUrl, false).then((res) => {
    console.log("Files added", res);
}).catch((err) => { console.log("Error in copy file", err) });

With the use of the above code. If I try to copy documents in the same site document libraries then it is working correctly. But if I try to copy documents from one site to another site. It threw the below error,

"Server relative urls must start with SPWeb.ServerRelativeUrl"

Kindly note that, I have used "sp-pnp-js": "^3.0.10". So, there is no replacement for the copyTo command. If I replace copyTo with copyByPath then PnP throws an error while building the solution.

Can anyone help me with the same?

Thanks

thedeepponkiya
  • 97
  • 1
  • 11

1 Answers1

0

Try using server relative URLs of files/library instead of complete/absolute URL.

For example:

// sourceFIleUrl is a server-relative url of a existing file
const sourceFIleUrl = "/sites/contoso1/Shared Documents/test.docx";
// destinationUrl is a server-relative url of a new file
const destinationUrl = `/sites/contoso2/Shared Documents/new-file.docx`;

await sp.web.getFileByServerRelativePath(sourceFIleUrl).copyByPath(destinationUrl, false, true);

Documentation: copy file by path


Similar threads:

  1. REST API error "Server relative urls must start with SPWeb.ServerRelativeUrl"
  2. GetFolderByServerRelativeUrl Rest API return Server relative urls must start with SPWeb.ServerRelativeUrl
Ganesh Sanap
  • 1,386
  • 1
  • 8
  • 18
  • Thanks for your quick response, I have updated my code as you suggested. Still, I have faced the same error. Kindly note that, I have used "sp-pnp-js": "^3.0.10". So, there is no replacement for copyTo command. If i replace copyTo with copyByPath then PnP throws an error. – thedeepponkiya Sep 04 '22 at 10:19
  • I have tried with server relative URLs of files/library instead of complete/absolute URL but still, I have faced the same issue while performing this operation between two subsites of the root site. Please let me know your thoughts on the same. – thedeepponkiya Sep 04 '22 at 12:04