javascript 未捕获(承诺):InvalidCharacterError:无法在“Window”上执行“atob”:要解码的字符串编码不正确

bnl4lu3b  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(359)

我试图将base64数据转换为文件obj,然后将其上传,其中base64Match是base64文件数据的数组。

async convertFile(data) {
        const base64Regex = /data:image\/\w+;base64,([\s\S]+)/; 
          const base64Match = this.Frm.value.content.match(base64Regex); 
          if (base64Match) { 
          const base64String = base64Match[1]; 
          } 
          let _that=this;
          base64Match.forEach(e => {
            let fileData=_that.dataURItoBlob(e);
            console.log('filedata',fileData.size);
          });
}

 dataURItoBlob(dataURI) {
    const byteString = window.atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([int8Array], { type: 'image/jpeg' });    
    return blob;
 }

但是我得到了这个错误:
ERROR错误:未捕获(承诺):InvalidCharacterError:无法在“Window”上执行“atob”:要解码的字符串编码不正确。错误:无法在“Window”上执行“atob”:要解码的字符串编码不正确。

任何解决方案来解决这个问题谢谢

yfwxisqw

yfwxisqw1#

不确定你的代码有什么问题,但在数据URI上使用.fetch并使用响应来创建缓冲区可能要容易得多,例如:

const dataUriToBlob = async (dataUri) => {
    const int8Array = await fetch(dataUri)
    .then(res => res.arrayBuffer())
    .then(buffer => new Uint8Array(buffer));
    const type = dataUri.slice(5, dataUri.indexOf(';'))
    const blob = new Blob([int8Array], { type });
    console.log(blob.size, blob.type);
}

dataUriToBlob(document.getElementById('img').src)
<img id="img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaoo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