Upload file to SharePoint library using File Control and PnP JS in SPFx webpart

In this article, we will learn how to upload files to the SharePoint library using File Control and PnP JS in SPFx web parts.

Pre-requisites – You have created SPFx webpart created and Select react Framework.

Please note that this can be used using No Javascript framework or Vue.js. Only difference would be how you rendering your input control and getting context. That is a different story.

We would use SP PnP js library module for SPFx web part.

Install it in your SPFx solution using below command.

npm install @pnp/sp --save

Added import statement in webpartcomponent.tsx file

import { sp } from "@pnp/sp";

Below should be your render method.

public render(): React.ReactElement<ISpFxWebCamProps> {
    
  return (
    <div className={ styles.maincontainer }>
      <input type="file" ref={(elm) => { this._input = elm; }}></input>
      <p>
      <button onClick={() => this.uploadFileFromControl()} >
                     Upload
                    </button>
                    </p>
    </div>
  
  );
}

Add our uploadFileFromControl method, please note here MyDocs is library name.

private uploadFileFromControl(){

  //Get the file from File DOM
var files = this._input.files;
var file = files[0];


   //Upload a file to the SharePoint Library
   sp.web.getFolderByServerRelativeUrl(this.props.context.pageContext.web.serverRelativeUrl + "/MyDocs")
   .files.add(file.name, file, true)
   .then((data) =>{
     alert("File uploaded sucessfully");
   })
   .catch((error) =>{
     alert("Error is uploading");
   });


}

That’s it, let us test this out.

Run gulp serve and browse workbench.aspx from your SharePoint site.

https://netflix.sharepoint.com/sites/strangerthings/_layouts/15/workbench.aspx

Select a file and click on upload.

 

Let go to library to check if document is uploaded.

 

Thanks for reading..Happy coding..!!!

(Visited 118 times, 1 visits today)