In this blog, we will use Async/Await function to upload files to sharepoint document library and to retrive the server relative url using SharePoint Framework.
What is Async/Await Function in React?
Async/Await function helps in handling asynchronous calls to behave it in a synchronous way.
Code Usage
-
- public GetFolderServerRelativeURL(file, FinalName, DocumentLibPath): Promise<any> {
- try {
- return new Promise((resolve) => {
- const spOpts: ISPHttpClientOptions = {
- body: file
- };
- var redirectionURL = this.props.siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('"+DocumentLibPath+"')/Files/Add(url='" + FinalName + "', overwrite=true)?$expand=ListItemAllFields"
- const response = this.props.spHttpClient.post(redirectionURL, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
- response.json().then(async (responseJSON: any) => {
- var serverRelURL = await responseJSON.ServerRelativeUrl;
- resolve(serverRelURL);
- });
- });
- });
- } catch (error) {
- console.log("Error in GetFolderServerRelativeURL " + error);
- }
-
- }
Usage
- this.GetFolderServerRelativeURL(file,"MyFile","TestDocumentLibrary");
Input the File object, Display Name and Document Library Name as parameter.
Note Make sure your webpart.ts contains site url and sphttpclient as shown below.
- public render(): void {
- const element: React.ReactElement<ISpFxRichTextEditorProps > = React.createElement(
- SpFxRichTextEditor,
- {
- spHttpClient: this.context.spHttpClient,
- siteUrl: this.context.pageContext.web.absoluteUrl,
- }
- );
- }
Please feel free to share your comments.
Hope this helps !!!!!