You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Jodit上传图片后如何在编辑器中添加图片?

在React的Jodit编辑器中插入后端返回URL的图片

你可以通过两种方式实现将后端返回的图片URL插入到编辑器中,根据需求选择即可:

方法一:通过process回调适配响应格式(自动插入)

如果后端返回的格式和Jodit默认预期不一致,用process回调转换响应结构后,编辑器会自动插入图片:

import JoditEditor from 'jodit-react';
import { useState } from 'react';

function EditorComponent() {
  const [content, setContent] = useState('');

  const editorConfig = {
    uploader: {
      url: 'http://localhost:3001/knowledgebase/upload',
      // 转换后端响应为Jodit识别的格式
      process: (resp) => {
        // 请根据后端实际返回结构调整字段
        return {
          success: true,
          file: resp.data.url
        };
      }
    }
  };

  return (
    <JoditEditor
      value={content}
      config={editorConfig}
      onChange={newContent => setContent(newContent)}
    />
  );
}

export default EditorComponent;

Jodit默认识别的响应格式是{"success": true, "file": "图片URL"},转换后编辑器会自动完成图片插入。

方法二:通过success回调手动插入图片(自定义属性)

如果需要给图片添加自定义类名、样式或alt文本,用success回调手动创建并插入图片元素:

import JoditEditor from 'jodit-react';
import { useState } from 'react';

function EditorComponent() {
  const [content, setContent] = useState('');

  const editorConfig = {
    uploader: {
      url: 'http://localhost:3001/knowledgebase/upload',
      success: function(resp) {
        // 获取后端返回的图片URL,根据实际响应调整
        const imageUrl = resp.data.url;
        
        // 创建自定义img元素
        const img = this.s.createInside.element('img');
        img.src = imageUrl;
        img.alt = '上传的图片';
        img.className = 'editor-upload-img';
        img.style.maxWidth = '100%';
        
        // 插入到编辑器光标位置
        this.s.insertNode(img);
      },
      error: (err) => {
        console.error('图片上传失败:', err);
      }
    }
  };

  return (
    <JoditEditor
      value={content}
      config={editorConfig}
      onChange={newContent => setContent(newContent)}
    />
  );
}

export default EditorComponent;

注意事项

  • 确保后端返回的图片URL可被前端正常访问(需处理跨域CORS问题)
  • 两种方法都要根据你后端实际的响应JSON结构调整URL的取值路径

内容的提问来源于stack exchange,提问作者Mustafa Dahodwala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 03:15:12