Unable to copy file from SharePoint different site document library with sp-pnp-js

542 Views Asked by At

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

1

There are 1 best solutions below

2
On

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