logo
Published on

File browse and select or upload using PnP File Picker in the SharePoint Framework (SPFx) webpart

This article explains how to implement the PnP File Picker in the SharePoint Framework (SPFx) web part.
The File Picker allows users to browse and select files from multiple sources like SharePoint, OneDrive, or even upload files directly.


📦 Install dependencies

Install the PnP React Controls and PnP JS libraries:

npm install @pnp/spfx-controls-react --save --save-exact
npm install @pnp/sp --save --save-exact

🧩 Configure the component

Create the state interface in your component file:

export interface ISpfxPnpFilepickerState {
  ImageURL: string;
}

💻 Implementation

Add the following render method to display the File Picker control:

public render(): React.ReactElement<ISpfxPnpFilepickerProps> {
  return (
    <div className={styles.spfxPnpFilepicker}>
      <img src={this.state.ImageURL} height={'150px'} width={'150px'}></img>
      <br></br>
      <br></br>
      <FilePicker
        label={'Select or upload image'}
        buttonClassName={styles.button}
        buttonLabel={'Images'}
        accepts={[".gif", ".jpg", ".jpeg", ".bmp", ".dib", ".tif", ".tiff", ".ico", ".png", ".jxr", ".svg"]}
        buttonIcon="FileImage"
        onSave={this.saveIntoSharePoint}
        onChanged={this.saveIntoSharePoint}
        context={this.props.context}
      />
    </div>
  );
}

Handle file upload or selection logic:

@autobind
private async saveIntoSharePoint(file: IFilePickerResult) {
  if (file.fileAbsoluteUrl == null) {
    file.downloadFileContent()
      .then(async r => {
        let fileresult = await sp.web.getFolderByServerRelativeUrl("/sites/TheLanding/Shared%20Documents/").files.add(file.fileName, r, true);
        this.setState({ ImageURL: document.location.origin + fileresult.data.ServerRelativeUrl });
      });
  }
  else {
    this.setState({ ImageURL: file.fileAbsoluteUrl });
  }
}

🚀 Deploy the solution

Build and package your SPFx solution:

gulp build
gulp bundle --ship
gulp package-solution --ship

Upload the .sppkg file to your App Catalog, deploy it, and add the web part to your SharePoint site.


🧭 Summary

You’ve successfully implemented the PnP File Picker control in SPFx.
It allows users to select or upload images directly from SharePoint, OneDrive, or local storage.


📂 GitHub Source

View full SPFx project on GitHub:File browse and select or upload using PnP File Picker in the SharePoint Framework (SPFx) webpart

GitHub
Calendar IconBook a demo