wangEditor —— 轻量级 web 富文本编辑器,配置方便,使用简单。
- 官网: www.wangEditor.com
- 文档: doc.wangEditor.com
- 源码: github.com/wangeditor-…(欢迎 star)
问题---从本地上传图片遇到的异步上传图片问题
先把编辑器初始化
const E = window.wangEditor
const editor = new E('#editor')
// 之后在中间位置添加代码进行配置
editor.create()
首先,得把编辑器的本地上传打通,具体如下步骤
1. 配置上传服务器端口
editor.config.uploadImgServer = this.action
2. 配置图片上传条件
editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp'] // 限制图片上传格式
editor.config.uploadImgMaxLength = 1 // 限制图片上传数量
接下来需要用到两个东西:customUploadImg(自定义图片上传事件)、uploadImgHooks(图片上传生命周期函数)
3. customUploadImg(自定义图片上传事件)
提交之前先使用formaData()处理图片文件
editor.config.customUploadImg = (resultFiles, insertImgFn) => {
const formData = new FormData()
const file = resultFiles[0]
formData.append('file', file)
api.upload(formData).then(res => {
const imgUrl = this.url + res.data.data
insertImgFn(imgUrl)
})
}
最后根据返回结果获取图片url地址
到这里其实就已经结束了,但这个图片上传的生命周期函数值得copy一下,以后或许会用到
3. uploadImgHooks(图片上传生命周期函数)
editor.config.uploadImgHooks = {
// 上传图片之前
before: function(xhr) {
console.log(xhr)
},
// 图片上传并返回了结果,图片插入已成功
success: function(xhr) {
console.log('success', xhr)
},
// 图片上传并返回了结果,但图片插入时出错了
fail: function(xhr, editor, resData) {
console.log('fail', resData)
},
// 上传图片出错,一般为 http 请求的错误
error: function(xhr, editor, resData) {
console.log('error', xhr, resData)
},
// 上传图片超时
timeout: function(xhr) {
console.log('timeout')
},
// 图片上传并返回了结果,想要自己把图片插入到编辑器中
// 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
customInsert: function(insertImgFn, result) {
// result 即服务端返回的接口
console.log('customInsert', result)
// insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
insertImgFn(result.data[0])
}
}