【问题标题】:javascript: downloaded file size different from content lengthjavascript:下载的文件大小与内容长度不同
【发布时间】:2015-02-18 03:09:41
【问题描述】:

我有一个 base64 字符串,我已解码并希望允许用户将其保存为文件。特别是,当我检查 decodedContent 的长度时,它是 11271 字节。

  var content = messageObj['data'];
var decodedContent = atob(content);
console.log(decodedContent.length);

然后我用了

var blob = new Blob([decodedContent], {type: 'application/octet-stream'});
window.open((window.URL || window.webkitURL).createObjectURL(blob));

提示用户保存decodedContent。当我检查保存的文件大小时,它显示 16892 字节,这与上述不同。知道为什么吗?

内容是从服务器发送的 base64 编码的 tar-ball 文件。

for i ,l in enumerate(to_download):
            if i == 1:
                break
            last_index = l.rfind('|')
            download_path = l[last_index+1:].strip()
            mda_url = '%s/%s'%(root_url, download_path)

            logger.debug('Downloading file %s/%s at %s', i, len(to_download), mda_url)

            mda_req = urllib2.Request(mda_url)
            mda_response = urllib2.urlopen(mda_req)
            f = StringIO.StringIO(mda_response.read())

            replace_path = mda_url.replace('/', '_')
            ti = TarInfo("%s.txt" %replace_path)
            ti.size = f.len

            tar.addfile(ti, f)

        tar.close()
        tar_file.close()

        with open("/Users/carrier24sg/Desktop/my.tar", 'rb') as f:
            tar_str = f.read()
        logger.info("Completed downloading all the requested files..")



    return tar_str

更新

缩小到 var decodedContent = atob(content) 的问题;或var blob = new Blob([decodedContent], {type: 'application/octet-stream'});

最后我设法使用了@Jeremy Bank 的答案here。他的第一个答案解决了内容长度不同的问题,但是当我检查校验和时,内容似乎不符。只有使用他的第二个答案的函数 b64toBlob 我才能解决这个问题。但是,我仍然不确定这里出了什么问题,所以我希望有人能对此有所了解。

【问题讨论】:

  • blob.size 显示什么?
  • blob.size 说 16892
  • 好的,你能举例说明decodedContent 中的内容吗?一种解释是atob 导致字符串包含多字节字符。例如,var p = atob('ddd'); var b = new Blob([p], {type:'application/octet-stream'}); console.log(b.size); /* 3 */ console.log(p.length); /* 2 */
  • @raina77ow,它是从服务器端发送的 base64 编码的 tarball 文件。我发布了我使用的 Python 代码片段。
  • base64 编码是在服务器端还是客户端完成的?可能是前者,否则您不必解码;仍然会很高兴澄清这一点。我的猜测是整个机制的某些部分将源材料视为一个字符串,而它实际上是一个字节序列(反之亦然)。

标签: javascript html google-chrome


【解决方案1】:

我认为问题在于 atomb() 会返回文件的基本 base64 版本。当你询问它的大小时,它会返回它包含的字节数。

当您从 base64 变量创建一个 blob 并询问其大小时,它将返回它将在您的计算机上填充多少空间。

这两件事是不同的,因为文件存储大小和编码大小不是一回事。而且它们在不同的平台上也有所不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多