javascript:下载的文件大小与内容长度不同

标签 javascript html google-chrome

我有一个解码后的 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 我才能解决这个问题。但是,我仍然不确定这里出了什么问题,所以我希望有人能对此有所说明。

最佳答案

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

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

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

关于javascript:下载的文件大小与内容长度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561681/

相关文章:

google-chrome - Chrome 网上应用店应用内付款 : Errors getting SKUs

javascript - jQuery 选择器不在 chrome 控制台中

Javascript 在旧浏览器中执行点击 html "image"

html - @media only screen and (max-width : --px) not working?

javascript - 如何有效地将相同的选项值分配给 Meteor 中的多个 Select 元素?

php - 正则表达式和xpath查询

javascript - Navigator.sendBeacon() 数据大小限制

css - 见 :hover state in Chrome Developer Tools

javascript - 如何在 Controller 中保留 html 中的变量?

javascript - 在 JavaScript 中声明一个对象供以后使用 - null 还是 {}?