解决vue3中 wangeditor插入图片 formdata 传值为空值的问题(已解决)
问题背景:
目前开发的项目中有一个富文本插入图片的需求,我使用的富文本是 wangeditor/editor,在使用其本身上传图片的功能,出现了formdata参数为空的情况,下面的解决方法完美解决了wangeditor富文本插入图片所遇到的formdata参数为空的问题
- 原本的代码写法
async customUpload(file, insertFn) {
let image = new Image()
const formData = new FormData()
formData.append('file', file)
try {
// 这里打印的formData是{}
const data = await uploadCover(formData)
if (data.resp_code === 0) {
image.onload = () => {
data.datas += `?width=${image.width}&height=${image.height}`
insertFn(joinPath(data.datas), file.name, '')
that.$message({
message: '插入成功',
type: 'success',
showClose: true
})
image = null
}
image.onerror = () => {
that.$message({
message: data.resp_msg,
type: 'warning',
showClose: true
})
}
image.src = joinPath(data.datas)
} else {
that.$message({
message: data.resp_msg,
type: 'warning',
showClose: true
})
}
} catch (uploadErr) {
that.$message({
message:
uploadErr.resp_msg ||
uploadErr.error ||
'网络似乎不通畅,请检查后再试',
type: 'warning',
showClose: true
})
}
- 更改过后的代码
async customUpload(file, insertFn) {
const formData = new FormData();
formData.append("file", file);
axios({ // 使用原生的axios进行调用接口 就可以解决问题
method: "post",
headers: {
Authorization: `Bearer ${getToken()}`
},
url: `${VITE_GLOB_API_URL}/上传图片后端的接收路径`,
data: formData
})
.then(data => {
if (data.data.resp_code === 0) {
insertFn(`${domain.value}${data.data.datas}`, file.name, "");
ElMessage({
message: "插入成功",
type: "success",
showClose: true
});
} else {
ElMessage({
message: `${data.data.resp_msg}`,
type: "warning",
showClose: true
});
}
})
.catch(error => {
ElMessage({
message:
error.resp_msg ||
error.error ||
"网络似乎不通畅,请检查后再试",
type: "warning",
showClose: true
});
});
- 最终效果