解决思路:
不修改原来的editormd文件
通过猴子补丁(monkey patch)的方式,替换editormd内部的上传方法。例如,找到image-dialog.js中处理上传的函数,保存原函数的引用,然后用自定义函数替换
// 初始化编辑器
function initEditor() {
// 保存原始图片上传处理函数
const originalImageUpload = editormd.prototype.executePlugin;
// 猴子补丁方式覆盖图片上传处理
editormd.prototype.executePlugin = function(pluginName, options) {
if (pluginName === "imageDialog") {
this.imageUploader = function() {
const file = this.files[0];
const loading = layer.msg('上传中...', {icon: 16, shade: 0.01});
// 创建与现有上传组件一致的FormData
const formData = new FormData();
formData.append('editormd-image-file', file); // 保持参数名称与现有系统一致
formData.append('filetype', 0); // 添加系统要求的参数
// 使用原始XMLHttpRequest发送保持请求结构
const xhr = new XMLHttpRequest();
xhr.open('POST', API.getApiUrl('index/upload'));
xhr.setRequestHeader('Authorization', 'Bearer ' + API.getToken());
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percent = (e.loaded / e.total * 100).toFixed(2) + '%';
layer.msg('上传进度: ' + percent, {icon: 16, shade: 0.01});
}
};
xhr.onload = function() {
layer.close(loading);