Upload and render image in draft-js based editor

Viewed 12492

I am trying to create a simple editor for writing a storyline. Right now I could show the html to markup in the editor where bold text are shown in bold and etc. I could also send the data in html form to server but I could not show the image in an editor and also could not upload the image in editor. I have created a codesandbox of it. Here is the link

https://codesandbox.io/s/5w4rp50qkp

The line of code is a bit huge. That is why I am posting the code in codesandbox where you can see the demo either.

Can anyone please help me to make this possible?

2 Answers

Set uploadEnable to true and call uploadCallBack

<Editor ref='textEditor'
       editorState={this.state.editorState}
       toolbar={{
            options: ['image',],
                        
            image: {
            uploadEnabled: true,
            uploadCallback: this.uploadCallback,
            previewImage: true,
            inputAccept: 'image/gif,image/jpeg,image/jpg,image/png,image/svg',
            alt: { present: false, mandatory: false },
            defaultSize: {
                 height: 'auto',
                 width: 'auto',
            },
         },
       }}
       onEditorStateChange={this.onEditorStateChange}
/>

then define your uploadCallback if you want to read file directly from local

uploadCallback = (file) => {
        return new Promise(
            (resolve, reject) => {
                if (file) {
                    let reader = new FileReader();
                    reader.onload = (e) => {
                        resolve({ data: { link: e.target.result } })
                    };
                    reader.readAsDataURL(file);
                }
            }
        );
    }

Or if you want to use a file server to keep files then you might want to upload image on server and then simply put the link

uploadCallback = (file) => {
    return new Promise((resolve, reject) => {
       const data = new FormData();
       data.append("storyImage", file)
       axios.post(Upload file API call, data).then(responseImage => {
            resolve({ data: { link: PATH TO IMAGE ON SERVER } });
       })
    });
}

Related