图片上传文件格式转换 base64、文件流、blob,wangeditor图片上传

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)
}

结束!这样就可以上传成功了!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值