vue wangeditor自定义上传图片
时间: 2025-02-06 17:57:36 浏览: 47
### 集成 WangEditor 并实现自定义图片上传
#### 安装依赖包
为了在 Vue 项目中使用 WangEditor,首先需要安装相应的 npm 包。对于 Vue 2 和 Vue 3 的不同版本,可以分别执行如下命令来安装:
```bash
npm install wangeditor --save
```
#### 初始化编辑器实例
创建一个新的组件用于承载富文本编辑器,在 `mounted` 生命周期钩子函数内初始化 editor 实例。
```javascript
import E from 'wangeditor'
export default {
name: "MyEditor",
mounted() {
const editor = new E(this.$refs.editorElem);
// 设置编辑区域高度
editor.config.height = 300;
// 开启调试模式
editor.config.debug = true;
// 更多配置...
editor.create();
}
}
```
#### 自定义图片上传服务器端点
通过设置 `uploadImgServer` 属性来自定义图片上传的目标 URL 地址[^1]。
```javascript
const editor = new E(this.$refs.editorElem);
// ...其他配置...
editor.config.uploadImgServer = '/your/custom/upload/api';
// 创建编辑器
editor.create();
```
#### 处理跨域请求与响应头
如果前端应用和后端 API 不在同一域名下,则需确保服务器返回合适的 CORS 响应头以便允许跨源资源共享。通常情况下,这涉及到调整 Web 服务器或框架中间件的配置以添加必要的 HTTP Access-Control-Allow-* 头部字段。
#### 添加额外参数到上传请求
有时可能还需要向上传请求附加一些额外的数据(比如 token 或者用户 ID),这时可以通过修改 `uploadFileName` 及 `withCredentials` 参数以及利用 `beforeUploadImg` 方法来进行处理。
```javascript
editor.config.withCredentials = true; // 如果需要携带 cookie 则开启此选项
editor.config.customUploadImg = function (resultFiles, insertImgFn) {
let formData = new FormData();
resultFiles.forEach(file => {
formData.append('file', file);
});
axios({
url: "/your/custom/upload/api",
method: 'post',
data: formData,
headers: { 'Content-Type': 'multipart/form-data' },
}).then(res => {
if (res.data.code === 200){
res.data.urls.map(url => insertImgFn(url));
}else{
console.error("Failed to upload images");
}
});
};
```
阅读全文
相关推荐


















