'React Draft Wysiwyg: Image Upload when I click the "Add" Button
On a React.js Application I try to make the https://jpuri.github.io/react-draft-wysiwyg/#/docs editor to upload an image and embend it into the editor's content.
So Far I managed to do this with this piece of code:
import React, { Component } from 'react';
import { Editor } from 'react-draft-wysiwyg';
import {convertFromRaw, convertToRaw, EditorState} from 'draft-js';
import "../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css"
import "../../node_modules/draft-js-image-plugin/lib/plugin.css"
export default class CustomEditor extends Component {
uploadCallback(file) {
return new Promise(
(resolve, reject) => {
var reader=new FileReader();
reader.onloadend = function() {
Meteor.call('fileStorage.uploadFile',reader.result,file.name,file.type,(err,response)=>{
console.log(response)
if(err){
reject(err)
}
resolve({ data: { link: response.data.url } });
})
}
reader.readAsDataURL(file);
}
);
}
render() {
const config={
image: { uploadCallback: this.uploadCallback }
}
return (
<div className="container-fluid">
<Editor toolbar={ config } />
</div>
)
}
}
But my problem is that the image uploading procces gets initiated when I select the file, what I want to initiate the upload process when I click on "Add" button as you see in the image bellow:
So how I can do that?
Solution 1:[1]
It's not possible to change this behavior.
The only option you can provide is uploadCallback, see the docs.
You can find the source for the upload code here, it's quite clear, it's not possible.
Solution 2:[2]
use toolbar props inside editor toolbar={image: { uploadCallback: uploadCallback }} and write a uploadCallback function like this below.
const uploadCallback = (file, callback) => {
console.log(file);
return new Promise((resolve, reject) => {
const reader = new window.FileReader();
console.log(reader);
reader.onloadend = async () => {
const form_data = new FormData();
form_data.append("file", file);
const res = await uploadFile(form_data);
setValue("thumbnail", res.data);
resolve({ data: { link: process.env.REACT_APP_API + res.data } });
};
reader.readAsDataURL(file);
});
};
const config = {
image: { uploadCallback: uploadCallback },
};
<Editor
toolbar={config}
editorState={editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={onEditorStateChange}
placeholder="Write your comment here"
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saurabh |
| Solution 2 | dEaD_ hOlicX |

