SPFx – Check Whether File Exists Using PnP in SharePoint WebParts

Sathish Nadarajan
 
Solution Architect
August 4, 2021
 
Rate this article
 
Views
2121

Usually while uploading any image or file, there might be scenario, whether the file with the same name is already present or not. Unfortunately, there is no direct method like isExists() present.

Though we have an option to override the existing version etc., I don’t want to do any action if the file is already present. For that, the below snippet was useful. Thought of sharing with the community.

public createImage = async (filename: string, serverRelativeUrl: string): Promise<any> => {
    try {

      const fileExists = await sp.web
        .getFileByServerRelativeUrl(`${serverRelativeUrl}/ Images/${filename}.svg`)
        .select('Exists').get()
        .then((d) => d.Exists)
        .catch(() => false);

//Basically, the above line will tell you whether the file is present on the 
//Images folder or not

      if (!fileExists) {
        await sp.web.getFolderByServerRelativeUrl(`${serverRelativeUrl}/ Images/`)
.files.add(`${filename}.svg`, <<blobValuefortheimage>>, true);
      }

 
    }
    catch (error) {
       //Log
    }
  }

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment