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
Leave a comment