【问题标题】:Error using 'atob' command - Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded使用“atob”命令时出错 - 无法在“窗口”上执行“atob”:要解码的字符串未正确编码
【发布时间】:2019-04-04 04:11:06
【问题描述】:

我需要将 base64 字符串解码为 PDF 文件。我正在使用此代码。但是window.atob命令总是报那个错误:Failed to execute 'atob' on 'Window':要解码的字符串没有正确编码。

我知道该文件是正确的,因为我已经使用将 base64 解码为 pdf 的网站对其进行了解码。 我不知道它是否有帮助,但我们正在使用 Aurelia 框架。

转换函数

function converBase64toBlob(content, contentType) {
        contentType = contentType || '';
        var sliceSize = 512;
        var byteCharacters = window.atob(content); //method which converts base64 to binary
        var byteArrays = [
        ];
        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }
        var blob = new Blob(byteArrays, {
            type: contentType
        }); //statement which creates the blob
        return blob;
    }

函数调用

self.blob = self.converBase64toBlob(result.contents[0].pdf.replace(/^[^,]+,/, ''), 'application/pdf');
                self.blobURL = URL.createObjectURL(blob);
                window.open(this.blobURL);

【问题讨论】:

  • 请注意完全确定,但我见过有人在末尾添加 '=' 最多 2 次,然后它就起作用了
  • 我不认为你可以在不破坏编码的情况下从 base64 .replace(/^[^,]+,/, '') 中删除字符
  • 感谢您的帮助,我已经尝试不使用 replace() 并且没有工作。关于最后添加'=',也没有用。

标签: javascript aurelia


【解决方案1】:

我找到了解决方案。 Api 正在返回带有字符“\”的 base64 字符串。所以我删除了所有这些,它工作得很好。

【讨论】:

  • 在我的例子中是 '=' 符号。无论如何,您的评论帮助我了解了这个想法,现在它可以工作了!
猜你喜欢
  • 1970-01-01
  • 2014-04-29
  • 2018-12-14
  • 2022-01-01
  • 2017-06-11
  • 2021-03-25
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
相关资源
最近更新 更多