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
  1. /* Get uploaded folder server relative url */
  2. public GetFolderServerRelativeURL(file, FinalName, DocumentLibPath): Promise<any> {
  3. try {
  4. return new Promise((resolve) => {
  5. const spOpts: ISPHttpClientOptions = {
  6. body: file
  7. };
  8. var redirectionURL = this.props.siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('"+DocumentLibPath+"')/Files/Add(url='" + FinalName + "', overwrite=true)?$expand=ListItemAllFields"
  9. const response = this.props.spHttpClient.post(redirectionURL, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
  10. response.json().then(async (responseJSON: any) => {
  11. var serverRelURL = await responseJSON.ServerRelativeUrl;
  12. resolve(serverRelURL);
  13. });
  14. });
  15. });
  16. } catch (error) {
  17. console.log("Error in GetFolderServerRelativeURL " + error);
  18. }
  19. }
Usage
  1. 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.
  1. public render(): void {
  2. const element: React.ReactElement<ISpFxRichTextEditorProps > = React.createElement(
  3. SpFxRichTextEditor,
  4. {
  5. spHttpClient: this.context.spHttpClient,
  6. siteUrl: this.context.pageContext.web.absoluteUrl,
  7. }
  8. );
  9. }

Please feel free to share your comments.
Hope this helps !!!!!