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

时间:2014-12-19 07:43:09

标签: javascript html5 google-chrome

我有一个base64字符串,我解码并希望允许用户将其保存为文件。特别是,当我检查decodeContent的长度时,它是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字节,这与上面所述的不同。知道为什么吗?

Content是从服务器发送的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才能解决这个问题。但是,我仍然不确定这里有什么问题,所以我希望有人可以对此有所了解。

1 个答案:

答案 0 :(得分:0)

我认为问题是atomb()返回了该文件的基本base64版本。当你要求它的大小时,它将返回它包含的字节。

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

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