自定义图片上传 Jodit 编辑器中的 URL

huangapple go评论112阅读模式
英文:

custom url in image upload jodit editor

问题

我已经实现了Jodit编辑器(react)https://github.com/jodit/jodit-react中的“插入图片”选项,您可以在其中上传图片,然后保存到编辑器的默认选项中。

我想知道如何使用自定义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" }
}
英文:

I have implemented Jodit Editor (react)https://github.com/jodit/jodit-react, Insert Image option, in which can you upload the image, which saves to the default option by the Editor,

I would like to know how to use custom url and insert the image in editor

Jodit default behaviour

config:{

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

}

Expected
How to do adding custom url

config:{

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

}

答案1

得分: 3

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

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

uploadImageButton = () => {
    Jodit.defaultOptions.controls.uploadImage = {
        name: '上传图像到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发送POST请求到Cloudinary。

// 对话框方法
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);
}

// 这个方法在上传完成后将图像插入编辑器中。
insertImage = (editor, url) => {
    const image = editor.selection.j.createInside.element('img');
    image.setAttribute('src', url);
    editor.selection.insertNode(image);
}

// 这个方法将图像发送到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);
        });

    return result;
}
英文:

In this repository, https://github.com/GilianMoa/jodit-editor-react
I'm uploading images with Cloudinary api.
Hope I can help you with this code.

I create a custom buttom:

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);
})
};
}

Then I create a method to open a dialog to pick the image and send to a service which send a post with the image file formData to 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;
}

答案2

得分: 3

我使用了 jodit-react 并成功上传了图片!以下是代码,希望能帮助您。

<JoditEditor
    ref={this.editor}
    value={this.state.content}
    config={{
        language: 'zh_cn',
        toolbarButtonSize: 'large',
        uploader: {
            url: '/manage/upload',  // 你的上传 API 地址
            insertImageAsBase64URI: false, // 不要插入 base64 图片
            imagesExtensions: ['jpg', 'png', 'jpeg', 'gif'],
            filesVariableName: function (t) {
                return 'files[' + t + ']';
            },
            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) {
                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) {
                const j = this;
                debugger;
                if (resp.files && resp.files.length) {
                    const tagName = 'img';
                    resp.files.forEach((filename: string, index: number) => {
                        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'
                );
            },
        },
    }}
/>

我已经测试通过了。

英文:

I use jodit-react and upload img success ! the code is here hope to help you.
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->
I have test ok.

huangapple
  • 本文由 发表于 2020年1月3日 18:16:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定