Upload CKeditor5 Images To SharePoint Document Library Using SharePoint Framework (SPFx)

In this blog, we will learn to upload all the images from the CKEditor5 (classic editor) editor area to SharePoint Document Library using SPFx.
 
CKEditor5 is a set of ready to use rich text editors that can be integrated with multiple platforms. In this blog, I have used CKEditor5 in my SharePoint Framework.
 
To integrate CKEditor5 to your SharePoint framework please refer to my previous blogs.
 
To integrate custom image upload plugin for CKEditor5 you can find in my previous blogs.
 
In this post, I will show you how to upload all the images from the CKEditor5 editor are to SharePoint online picture library.
 
Note
Ckeditor5 Classic Editor is not yet supported in the IE11 browser.
 
The below code is tested in Chrome, Mozilla, and Edge.
 
Steps Involved
 
The below function has to be used after integrating the image upload plugin in CKEditor5 which is shared in my previous posts.
 
Parameters
 
spPictureLibrary - SharePoint Picture Library to hold images.
CKeditorEventData - CKEditor5 event which is stored in state variable while initializing the CKEditor5.
 
The below function replaces the image URL which contains "base64" data format with SharePoint server relative URL and gets the modified image URLs.
  1. /* Upload files to sharepoint library */    
  2.     public async AddImagestoSPDocLib(spPictureLibrary,CKeditorEventData) {    
  3.         try {    
  4.             var fileContent = CKeditorEventData.getData();    
  5.             const imgObj = $(fileContent).find('img');    
  6.             let base64Obj = [];    
  7.             if (imgObj.length > 0) {    
  8.                 imgObj.toArray().forEach((img) => {    
  9.                     var base64string = img["currentSrc"];    
  10.                     if (base64string.split(',')[0].indexOf('base64') >= 0) {    
  11.                         base64Obj.push(img);    
  12.                     }    
  13.                 });    
  14.             }    
  15.             let fileArray = [];    
  16.             let promises = [];    
  17.             if (base64Obj.length > 0) {    
  18.                 base64Obj.forEach((img, indx) => {    
  19.                     var base64string = img["currentSrc"];    
  20.                     if (base64string.split(',')[0].indexOf('base64') >= 0) {    
  21.                         var date = new Date();    
  22.                         var guid = date.valueOf();    
  23.                         var fileName = guid + ".png";    
  24.                         var file = this.ConvertBase64ToFile(base64string, fileName);    
  25.                         fileArray.push([{ base64: base64string, elemID: indx }]);    
  26.                         promises.push(this.GetServerRelativeURL(file, spPictureLibrary));    
  27.                     }    
  28.                 });    
  29.                 await Promise.all(promises)    
  30.                     .then((modifiedContent) => {    
  31.                         for (let y = 0; y < fileArray.length; y++) {    
  32.                             if (fileArray[y][0].elemID == y) {    
  33.                                 fileContent = fileContent.replace(fileArray[y][0].base64, modifiedContent[y]);    
  34.                             }    
  35.                         }    
  36.                     })    
  37.                     .catch((error) => {    
  38.                         alert("Error while processing the promise call " + error)    
  39.                     });    
  40.                 return fileContent;    
  41.             } else {    
  42.                 return fileContent;    
  43.             }    
  44.         } catch (error) {    
  45.             console.log('Error in  AddImagestoSPDocLib ' + error);    
  46.         }    
  47.     }    
The below method converts Base64 to File object. 
  1. /* Convert Base64 data as file object  */    
  2.     public ConvertBase64ToFile(dataURI, fileName) {    
  3.         try {    
  4.             if (dataURI.split(',')[0].indexOf('base64') >= 0) {    
  5.                 var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1],    
  6.                     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);    
  7.                 while (n--) {    
  8.                     u8arr[n] = bstr.charCodeAt(n);    
  9.                 }    
  10.                 return new File([u8arr], fileName, { type: mime });    
  11.             }    
  12.         }    
  13.         catch (error) {    
  14.             console.log("Error in ConvertBase64ToFile " + error);    
  15.         }    
  16.     }    
Upload images to Sharepoint picture library and retrieve the server relative urls of the images.
 
Note
Make sure your "webpart.ts" should contain 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. }   
  1. /*Get server relative url of a uploaded image */    
  2.     public GetServerRelativeURL(file, spPictureLibrary): Promise<any> {    
  3.         try {    
  4.             return new Promise((resolve) => {    
  5.                 setTimeout(() => {    
  6.                     const spOpts: ISPHttpClientOptions = {    
  7.                         body: file    
  8.                     };    
  9.                     var redirectionURL = this.props.siteUrl + "/_api/Web/Lists/getByTitle('"+spPictureLibrary+"')/RootFolder/Files/Add(url='" + file.name + "', overwrite=true)?$expand=ListItemAllFields"    
  10.                     const response = this.props.spHttpClient.post(redirectionURL, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {      
  11.                         response.json().then(async (responseJSON: any) => {      
  12.                           console.log(responseJSON.ServerRelativeUrl);    
  13.                           var serverRelURL = await responseJSON.ServerRelativeUrl;    
  14.                           resolve(serverRelURL);        
  15.                         });      
  16.                     });    
  17.                 }, Math.floor(Math.random() * 1000));    
  18.             });    
  19.         } catch (error) {    
  20.             console.log("Error in GetServerRelativeURL" + error );    
  21.         }    
  22.     }   
Usage
 
Parameters - SharePoint Picture Library
 
CKEditor5 event - captured while initializng the editor (eg : this.state.CKEditorEvent)
  1. this.AddImagestoSPDocLib("TestPictureLibrary",ckeditorEvent).then((modifiedHtmlContent) =>{    
  2.         console.log(modifiedHtmlContent);    
  3. });  
Please feel free to share your comments.
 
Hope this helps !!!!!