图片url转为base64再转为File上传

当你只有图片路径url怎么上传呢?

 // item为包含img片段,用getAsString转为string类型
await this.urlToFile(item, 'name'),then(file => {
  this.upload(file)
}
urlToFile (item, fileName) {
    const self = this
    return new Promise(function (resolve, reject) {
      try {
        item.getAsString(function (str) {
          const imageUrl = (str.match(/img src="(\S*)"/) || [])[1] || '' // 截取图片url
          if (!imageUrl) {
            self.$message.error('读取图片失败')
            reject(new Error('读取图片失败'))
            return
          }
          let image = new Image()
          image.src = imageUrl
          image.setAttribute('crossOrigin', 'anonymous') // 跨域
          const imgPromise = new Promise(function (resolve, reject) {
            image.onload = function () {
              let canvas = document.createElement('canvas') // 创建canvas元素
              const width = image.width // 确保canvas的尺寸和图片一样
              const height = image.height
              canvas.width = width
              canvas.height = height
              canvas.getContext('2d').drawImage(image, 0, 0, width, height) // 将图片绘制到canvas中
              const dataURL = canvas.toDataURL('image/png') // 转换图片为dataURL
              const arr = dataURL.split(',')
              const mime = arr[0].match(/:(.*?);/)[1]
              const bstr = atob(arr[1])
              let n = bstr.length
              const u8arr = new Uint8Array(n)
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
              }
              const file = new File([u8arr], fileName, { type: mime })
              resolve(file)
            }
            image.onerror = () => {
              self.$message.error('读取图片失败')
              reject()
            }
          })
          imgPromise.then(file => {
            resolve(file)
          })
        })
      } catch (e) {
        self.$message.error('读取图片失败')
        reject()
      }
    })
  }
upload(file) {
  const params = new FormData
  params.append('file', file)
  this.$http.post('/upload', params).then(res => {})
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值