how to insert file in library and insert data from that file in sharepoint online in SPFX react
1 Answer
Here is a sample code snippet that demonstrates how to upload a file to a library and insert data from that file in SharePoint Online using SPFX React and File Upload API:
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/files";
async function uploadFile(file: File, libraryName: string) {
try {
const fileUrl = '/${libraryName}/${file.name}';
// Upload the file to the library
await sp.web.getFolderByServerRelativeUrl('/${libraryName}').files.add(file.name, file, true);
// Get the file's content
const response = await sp.web.getFileByServerRelativeUrl(fileUrl).getBuffer();
const content = new TextDecoder().decode(response);
// Insert the file's content in SharePoint using the REST API
const list = sp.web.lists.getByTitle(libraryName);
const listItem = await list.items.add({
Title: file.name,
Content: content
});
} catch (error) {
console.log(error);
}
}
-
hey i use the same code but i'm getting error Property 'getFolderByServerRelativeUrl' does not exist on type 'IWeb & IInvokable<any>'. Did you mean 'getFolderByServerRelativePath'?ts(2551) web.d.ts(24, 9): 'getFolderByServerRelativePath' is declared here. so how can i resolve this– KajalCommented Sep 5, 2023 at 12:55