2014-12-19 66 views
6

我有一个base64字符串,我解码并希望允许用户将其保存为文件。特别是,当我检查decodeContent的长度时,它是11271字节。javascript:下载的文件大小与内容长度不同

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 

UPDATE

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

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

+0

'blob.size'显示什么? – raina77ow 2014-12-19 07:57:12

+0

blob.size说16892 – goh 2014-12-19 08:12:18

+0

好的,你可以举一个'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 2014-12-19 09:25:15

回答

0

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

当你从base64变量创建一个blob并询问它的大小时,它会返回它将填满计算机的空间。

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

相关问题