
本文详解如何通过配置 jodit 的 `uploader` 选项,实现将本地图片自动上传至指定后端接口(如 `/files`),并正确插入返回的图片 url 到编辑器中,无需手动处理文件选择与 dom 插入。
Jodit 编辑器内置了灵活的文件上传机制,关键在于正确配置 config.uploader 对象。它接管从用户选择文件、构造请求、发送上传、解析响应到最终插入图片的全流程。你无需重写文件选择逻辑或手动调用 insertImage() —— 只需告诉 Jodit:上传地址在哪、数据怎么打包、成功响应长什么样、图片 URL 在哪取。
以下是完整、可直接集成的 uploader 配置(已适配你的后端要求):
uploader: {
insertImageAsBase64URI: false, // 禁用 base64,强制走 URL 插入
imagesExtensions: ['jpg', 'jpeg', 'png', 'gif'], // 允许的图片格式
withCredentials: false, // 如需携带 cookie 或 auth header,设为 true
format: 'json', // 告知 Jodit 期望 JSON 响应
method: 'POST',
url: 'http://localhost:3000/files', // 你的后端上传接口
headers: {
// 注意:multipart/form-data 由浏览器自动设置 boundary,此处不要手动指定 Content-Type
},
prepareData: function (data) {
// data 是 FormData 实例;this.file 是用户选中的 File 对象
data.append('file', this.file);
return data;
},
isSuccess: function (resp) {
// 自定义判定逻辑:只要响应体有 data 字段(即字符串 URL),即视为成功
return typeof resp === 'string' || (resp && typeof resp.data === 'string');
},
process: function (resp) {
// 关键:将后端返回的纯字符串 URL 封装为 Jodit 识别的格式
const url = typeof resp === 'string' ? resp : resp.data;
return {
files: [url], // 必须是数组,且第一个元素即为要插入的图片 URL
path: '',
baseurl: '',
error: !url ? 1 : 0,
msg: !url ? 'Upload failed' : ''
};
},
defaultHandlerSuccess: function (data, resp) {
const files = data.files || [];
if (files.length > 0) {
// 插入第一张图片,宽高可选(null 表示保持原始尺寸)
this.selection.insertImage(files[0], null, 250);
}
},
defaultHandlerError: function (resp) {
const msg = typeof resp === 'string' ? resp : (resp.msg || 'Upload error');
this.events.fire('errorPopup', this.i18n(msg));
}
}? 重要注意事项:
- ✅ 后端必须返回纯字符串 URL(如 "https://example.com/uploads/abc.jpg"),或兼容 { "data": "..." } 结构;
- ❌ 不要在 headers 中手动设置 'Content-Type': 'multipart/form-data' —— 浏览器会自动添加带正确 boundary 的头,手动设置会导致请求失败;
- ⚠️ 若后端需要认证(如 Bearer Token),请在 headers 中添加 Authorization 字段,并确保 withCredentials: true(若跨域);
- ? prepareData 是唯一需要你干预的数据组装环节;process 负责“翻译”响应为 Jodit 内部格式;isSuccess 和 defaultHandlerSuccess 控制流程分支。
将上述 uploader 配置整合进你原有的 config 对象中,替换掉空的 uploader: {},即可立即生效。用户点击工具栏「图片」按钮或拖拽图片到编辑区时,Jodit 将自动完成上传与插入,体验无缝、专业。
最后提醒:务必在开发环境确认 CORS 配置允许 localhost:3000(前端)访问你的后端服务,否则请求会被浏览器拦截。










