sp-pnp-js to perform copy/paste file operations between subsites in SharePoint online 365



Perform copy/paste file operations between two subsites using sp-pnp-js in O365 SharePoint online. If both subsites are under the same site collection.

Copy the file from Subsite 1 (“/SourceSite”) and paste it into Subsite 2 (“/DestinationSite”).

Prerequisite: Install npm package for sp-pnp-js (npm install sp-pnp-js@3.0.10)

Example:

  • Site Collection: https://<Tenant Name>.sharepoint.com
  • Subsite 1: https://<Tenant Name>.sharepoint.com/SourceSite
  • Subsite 2: https://<Tenant Name>.sharepoint.com/DestinationSite

Created file-operations component in angular 11 and it contained only one button for “Copy To” and perform the file operation between two subsites.

  • file-operations.component.html
    <button type="button" (click)="copyFile()">Copy To</button>
  • file-operations.component.ts
    import { Component, OnInit } from '@angular/core';
    import pnp, { sp, Web } from "sp-pnp-js";
    declare var _spPageContextInfo;
    
    @Component({
      selector: 'app-file-operations',
      templateUrl: './file-operations.component.html',
      styleUrls: ['./file-operations.component.css']
    })
    
    export class FileOperationsComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit(): void {
      }
    
      copyFile() {
        const fromLocation = '/SourceSite/Shared%20Documents/Annotations/6f8b2849-e6bf-4664-97cd-ca8bd29c4219/' + encodeURIComponent('Test &- 50% Do#^{_cuments.jpg');
        const toLocation = '/DestinationSite/Shared%20Documents/Annotations/539ee0ab-29d4-4966-8818-bed78e748c8c/' + encodeURIComponent('Test &- 50% Do#^{_cuments.jpg');
        const targetFolder = '/DestinationSite/Annotations/539ee0ab-29d4-4966-8818-bed78e748c8c';
        const targetWeb = _spPageContextInfo.siteAbsoluteUrl + '/DestinationSite';
    
        const file = sp.web.getFileByServerRelativePath(fromLocation);
        file.getBlob().then(blob => {
          const web = new Web(targetWeb);
          return web.getFolderByServerRelativePath(targetFolder)
            .files.add(toLocation, blob);
        }).then((res) => {
          console.log("Files pasted successfully in destination site", res);
        }).catch((err) => {
          console.log("Error in copy file", err);
        });
      }
    }

Result

  • Published this file-operations component on Subsite 1 (“/SourceSite”) home page.
  • Now, click on the “Copy To” button and it will copy the document “Test &- 50% Do#^{_cuments.jpg” from Subsite 1 (“/SourceSite”) and paste it into Subsite 2 (“/DestinationSite”).
  • Copy from Subsite 1 (“/SourceSite”) Location: /SourceSite/Shared%20Documents/Annotations/6f8b2849-e6bf-4664-97cd-ca8bd29c4219/
  • Paste into Subsite 2 (“/DestinationSite”) Location: /DestinationSite/Annotations/539ee0ab-29d4-4966-8818-bed78e748c8c/

 

Add comment

BlogList

MonthList

TagCloud

BlogList

MonthList

TagCloud