CKEditor 5 React custom image upload

2020-08-01 06:24发布

问题:

I have spent all day trying to get CKEditor with React to work. Everything seems to be okay except the images. I

I have a way to upload the images to my server already (azure). ALL I NEED is to know how to connect it to the CKEditor with React! I keep getting the error "Upload adapter is not defined."

<CKEditor
          editor={ ClassicEditor }
          data={this.state.body ? this.state.body : "<p>Body text...</p>"}
          onInit={ editor => {
            // You can store the "editor" and use when it is needed.
            console.log( 'Editor is ready to use!', editor );
          } }
          onChange={ ( event, editor ) => {
            const data = editor.getData();
            console.log( { event, editor, data,}, "DATA" );
          } }
          // config={upload=this.uploadImage()}
          
        />

I'm guessing it has something to do with the config file? I already have the function that uploads the file and returns the URL, I just don't know where to add that into the CKEditor in React.

回答1:

That error means there is no upload adapter connected.

First, you'll need to implement your own Custom Upload Adapter which handles uploading the images to the server. There’s a sample in this Stack Overflow response

And then, you link the editor to your upload adapter in your onInit method. Like so:

<CKEditor
    editor={ClassicEditor}
    data={this.state.body ? this.state.body : "<p>Body text…</p>"}
    onInit={editor => {
       // Connect the upload adapter using code below 
       editor.plugins.get("FileRepository").createUploadAdapter = function(loader) {
          return new UploadAdapter(loader);
       };
       console.log("Editor is ready to use!", editor);
    }}
    onChange={(event, editor) => {
        const data = editor.getData();
        console.log({ event, editor, data }, "DATA");
    }}
/>

UploaderAdapter in the code is the name of your UploadAdapter class implementation.