wangEditor上传本地图片,如何配置header
时间: 2025-01-15 12:59:40 浏览: 84
### 使用 wangEditor 上传本地图片并配置 Header
在 Vue3 或其他前端框架中使用 `wangEditor` 富文本编辑器时,如果需要上传本地图片至服务器,并且希望在此过程中设置 HTTP 请求头(Header),可以通过自定义上传函数来实现这一需求。
当调用 `uploadImage` 方法时,可以传递一个对象作为参数,在这个对象里指定 `customUpload` 属性以及相应的回调处理逻辑。在这个回调内部,则能够通过 XMLHttpRequest 来手动控制整个上传过程,从而允许修改请求头部信息[^1]。
下面是一个具体的例子展示如何完成这项工作:
```javascript
import { createEditor } from 'wangeditor'
// 创建 editor 实例
const editor = createEditor({
selector: '#div1', // 绑定的 DOM 节点的选择器
})
editor.config.customUploadImg = function (resultFiles, insertImageFn) {
const xhr = new XMLHttpRequest();
let formData = new FormData();
resultFiles.forEach(file => {
formData.append('file[]', file);
});
xhr.open('POST', '/your/upload/api/url');
// 设置 headers
xhr.setRequestHeader('Authorization', 'Bearer your_token_here');
xhr.setRequestHeader('X-Custom-Header', 'CustomValue');
xhr.send(formData);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
const responseJson = JSON.parse(xhr.responseText);
// 假设返回的数据结构如下:
/*
{
"errno": 0,
"data": [
{"url": "..."},
...
]
}
*/
const imgUrls = responseJson.data.map(item => item.url);
insertImageFn(imgUrls);
} catch(e){
console.error('Failed to parse server response:', e.message);
}
}
};
};
editor.create(); // 初始化编辑器实例
```
此代码片段展示了怎样利用 `XMLHttpRequest` 对象来自定义图片上传流程,并向其中加入额外的 Headers 字段。需要注意的是实际开发环境中应当替换 `/your/upload/api/url` 和 `'Bearer your_token_here'` 这些占位符为真实的 API 地址和个人令牌值。
阅读全文
相关推荐

















