0

我已经实现了 Jodit Editor (react) https://github.com/jodit/jodit-react , Insert Image 选项,你可以在其中上传图片,由 Editor 保存到默认选项,

我想知道如何使用自定义 url 并在编辑器中插入图像

Jodit 默认行为

config:{

 readonly: false,
        enableDragAndDropFileToEditor: true,        
        uploader: { url: "https://xdsoft.net/jodit/connector/index.php?action=fileUpload"}

}

预期如何添加自定义网址

config:{

 readonly: false,
        enableDragAndDropFileToEditor: true,        
        uploader: { url: "www.xyz.com/upload"}

}
4

2 回答 2

1

在这个存储库中,https://github.com/GilianMoa/jodit-editor-react 我正在使用 Cloudinary api 上传图像。希望我可以帮助您使用此代码。

我创建了一个自定义按钮:

uploadImageButton = () => {
        Jodit.defaultOptions.controls.uploadImage = {
            name: 'Upload image to Cloudinary',
            iconURL: "https://www.kindpng.com/picc/m/261-2619141_cage-clipart-victorian-cloud-upload-icon-svg-hd.png",
            exec: (async (editor) => {
                await this.imageUpload(editor);
            })
        };
    }

然后我创建一个方法来打开一个对话框来选择图像并发送到一个服务,该服务将带有图像文件 formData 的帖子发送到 cloudinary。

//dialog method
imageUpload = (editor) => {
    
            const input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.click();
    
            input.onchange = async function () {
    
                const imageFile = input.files[0];
    
                if (!imageFile) {
                    return;
                }
    
                if (!imageFile.name.match(/\.(jpg|jpeg|png)$/)) {
                    return;
                }
    
                const imageInfo = await FileUpload(imageFile);;
    
                this.insertImage(editor, imageInfo.url);
    
            }.bind(this);
        }

//this method insert the image inside the editor after the upload is done.
        insertImage = (editor, url) => {
            const image = editor.selection.j.createInside.element('img');
            image.setAttribute('src', url);
            editor.selection.insertNode(image);
        }




// this method send the image to cloudinary
    export const FileUpload = async (file) => {
        let result = null;
    
        let formData = new FormData();
        formData.append('file', file);
        formData.append('upload_preset', `${process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET}`);
    
        await fetch(`https://api.cloudinary.com/v1_1/${process.env.REACT_APP_CLOUDINARY_CLOUD_NAME}/image/upload`, {
            method: 'POST',
            body: formData
        })
            .then((response) => response.json())
            .then((data) => {
                result = data;
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    
        return result;
    }
于 2020-07-26T18:48:44.477 回答
1

我使用 jodit-react 并上传 img 成功!代码在这里希望对您有所帮助。

 <JoditEditor
                ref={this.editor}
                value={'this.state.content'}
                config={{
                  language: 'zh_cn',
                  toolbarButtonSize: 'large',
                  uploader: {
                    url: '/manage/upload',  //your upload api url
                    insertImageAsBase64URI: false, not inster base64
                    imagesExtensions: ['jpg', 'png', 'jpeg', 'gif'],
                    //headers: {"token":`${db.token}`},
                    filesVariableName: function (t) {
                      return 'files[' + t + ']';
                    }, //"files",
                    withCredentials: false,
                    pathVariableName: 'path',
                    format: 'json',
                    method: 'POST',
                    prepareData: function (formdata) {
                      return formdata;
                    },
                    isSuccess: function (e) {
                      debugger;
                      return e.success;
                    },
                    getMessage: function (e) {
                      return void 0 !== e.data.messages && Array.isArray(e.data.messages)
                        ? e.data.messages.join('')
                        : '';
                    },
                    process: function (resp: any) { //success callback transfrom data to defaultHandlerSuccess use.it's up to you.
                      let files = [];
                      files.unshift(resp.data);
                      return {
                        files: resp.data,
                        error: resp.msg,
                        msg: resp.msg,
                      };
                    },
                    error: function (this: any, e: Error) { 
                      this.j.e.fire('errorMessage', e.message, 'error', 4000);
                    },
                    defaultHandlerSuccess: function (this: Uploader, resp: IUploaderData) { // `this` is the editor.
                      const j = this;
                      debugger;
                      if (resp.files && resp.files.length) {
                        const tagName = 'img';
                        resp.files.forEach((filename: string, index: number) => { //edetor insertimg function
                          const elm = j.createInside.element(tagName);
                          elm.setAttribute('src', filename);
                          j.s.insertImage(elm as HTMLImageElement, null, j.o.imageDefaultWidth);
                        });
                      }
                    },
                    defaultHandlerError: function (this: any, e) {
                      this.j.e.fire('errorMessage', e.message);
                    },
                    contentType: function (e) {
                      return (
                        (void 0 === this.jodit.ownerWindow.FormData || 'string' == typeof e) &&
                        'application/x-www-form-urlencoded; charset=UTF-8'
                      );
                    },
                  },
                }}
              />
我测试好了。

于 2020-09-23T02:52:04.927 回答