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.
-
- public async AddImagestoSPDocLib(spPictureLibrary,CKeditorEventData) {
- try {
- var fileContent = CKeditorEventData.getData();
- const imgObj = $(fileContent).find('img');
- let base64Obj = [];
- if (imgObj.length > 0) {
- imgObj.toArray().forEach((img) => {
- var base64string = img["currentSrc"];
- if (base64string.split(',')[0].indexOf('base64') >= 0) {
- base64Obj.push(img);
- }
- });
- }
- let fileArray = [];
- let promises = [];
- if (base64Obj.length > 0) {
- base64Obj.forEach((img, indx) => {
- var base64string = img["currentSrc"];
- if (base64string.split(',')[0].indexOf('base64') >= 0) {
- var date = new Date();
- var guid = date.valueOf();
- var fileName = guid + ".png";
- var file = this.ConvertBase64ToFile(base64string, fileName);
- fileArray.push([{ base64: base64string, elemID: indx }]);
- promises.push(this.GetServerRelativeURL(file, spPictureLibrary));
- }
- });
- await Promise.all(promises)
- .then((modifiedContent) => {
- for (let y = 0; y < fileArray.length; y++) {
- if (fileArray[y][0].elemID == y) {
- fileContent = fileContent.replace(fileArray[y][0].base64, modifiedContent[y]);
- }
- }
- })
- .catch((error) => {
- alert("Error while processing the promise call " + error)
- });
- return fileContent;
- } else {
- return fileContent;
- }
- } catch (error) {
- console.log('Error in AddImagestoSPDocLib ' + error);
- }
- }
The below method converts Base64 to File object.
-
- public ConvertBase64ToFile(dataURI, fileName) {
- try {
- if (dataURI.split(',')[0].indexOf('base64') >= 0) {
- var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1],
- bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- return new File([u8arr], fileName, { type: mime });
- }
- }
- catch (error) {
- console.log("Error in ConvertBase64ToFile " + error);
- }
- }
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.
- public render(): void {
- const element: React.ReactElement<ISpFxRichTextEditorProps > = React.createElement(
- SpFxRichTextEditor,
- {
- spHttpClient: this.context.spHttpClient,
- siteUrl: this.context.pageContext.web.absoluteUrl,
- }
- );
- }
-
- public GetServerRelativeURL(file, spPictureLibrary): Promise<any> {
- try {
- return new Promise((resolve) => {
- setTimeout(() => {
- const spOpts: ISPHttpClientOptions = {
- body: file
- };
- var redirectionURL = this.props.siteUrl + "/_api/Web/Lists/getByTitle('"+spPictureLibrary+"')/RootFolder/Files/Add(url='" + file.name + "', overwrite=true)?$expand=ListItemAllFields"
- const response = this.props.spHttpClient.post(redirectionURL, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
- response.json().then(async (responseJSON: any) => {
- console.log(responseJSON.ServerRelativeUrl);
- var serverRelURL = await responseJSON.ServerRelativeUrl;
- resolve(serverRelURL);
- });
- });
- }, Math.floor(Math.random() * 1000));
- });
- } catch (error) {
- console.log("Error in GetServerRelativeURL" + error );
- }
- }
Usage
Parameters - SharePoint Picture Library
CKEditor5 event - captured while initializng the editor (eg : this.state.CKEditorEvent)
- this.AddImagestoSPDocLib("TestPictureLibrary",ckeditorEvent).then((modifiedHtmlContent) =>{
- console.log(modifiedHtmlContent);
- });
Please feel free to share your comments.
Hope this helps !!!!!