wangeidtor图片上传格式的转换
上篇说到传了富文本的自定义图片上
https://blog.csdn.net/weixin_42439024/article/details/107635918
现在说说图片上传格式的转换
this.editor.customConfig.customUploadImg = async (files, insert) => {})
在这里执行自定义的axios请求,但是我们会发现返回的files文件流,直接使用json格式发给接口,是为空的,导致上传失败。
这时候我们就需要进行格式转换,把file文件流转成base64,再转blob格式。
this.editor.customConfig.customUploadImg = async (files, insert) => {
this.filesToBase64(files) // 把file文件流转成base64
}
// 将文件流转换为base64
filesToBase64(files) {
let _this = this
files.map(item => {
var reader = new FileReader()
reader.onload = function(e) {
_this .uploadImage(e.target.result, item) // 执行上传图片的接口请求
}
reader.readAsDataURL(item)
})
}
// 执行上传图片
uploadImage(base64, file) {
let _this = this
let formdata = new FormData() // 创建form对象
this.Base64toBlob({
base64,
success(blob) {
// 上传完成,表单储存数组
_this .uploadImgForm.file = file
// 转formData格式发送数据
Object.keys(_this .uploadImgForm).forEach((key) => {
formdata.append(key, _this .uploadImgForm[key])
})
axios.post(window.SITE_CONFIG.baseUrl + 'common/upload/uploadFile', formdata, {
headers: {
'token': _this .$cookie.get('token'),
'Content-Type': 'multipart/form-data'
}
}).then(res => {
Message.success('上传成功')
var url = res.data.data.uploadPath
_this .editor.cmd.do('insertHtml', '<img src="' + window.SITE_CONFIG.uploadImage + url + '" style="max-width:100%;"/>') //将图片插入到HTML内容中
})
}
}).catch(() => {
})
}
// 将base64 转换为blob型
Base64toBlob({ base64, success }) {
var arr = base64.split(',')
var mime = arr[0].match(/:(.*?);/)[1]
var bstr = atob(arr[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
let blob = new Blob([u8arr], { type: mime })
success(blob)
}
结束!这样就可以上传成功了!