Tôi có chuỗi base64 mà tôi đã giải mã và muốn cho phép người dùng lưu tệp này dưới dạng tệp. Đặc biệt, khi tôi kiểm tra độ dài của decodedContent, nó là 11271 byte.javascript: kích thước tệp đã tải xuống khác với độ dài nội dung
var content = messageObj['data'];
var decodedContent = atob(content);
console.log(decodedContent.length);
Sau đó, tôi sử dụng
var blob = new Blob([decodedContent], {type: 'application/octet-stream'});
window.open((window.URL || window.webkitURL).createObjectURL(blob));
Để nhắc nhở người dùng để lưu decodedContent
. Khi tôi kiểm tra kích thước tệp đã lưu, nó nói 16892 byte, khác với những gì được nêu ở trên. Bất kỳ ý tưởng tại sao?
Nội dung là tệp tar-ball được mã hóa base64 được gửi từ máy chủ.
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
CẬP NHẬT:
thu hẹp cho vấn đề là với một trong hai var decodedContent = atob(content)
; hoặc var blob = new Blob([decodedContent], {type: 'application/octet-stream'});
Cuối cùng tôi đã quản lý để sử dụng câu trả lời của @Jeremy Bank here. Câu trả lời đầu tiên của ông giải quyết vấn đề chiều dài nội dung là khác nhau, nhưng khi tôi kiểm tra tổng kiểm tra, nội dung dường như không kiểm đếm. Chỉ sử dụng hàm b64toBlob của câu trả lời thứ hai của tôi tôi mới giải quyết được điều này. Tuy nhiên, tôi vẫn không chắc chắn những gì là sai ở đây, vì vậy tôi hy vọng ai đó có thể làm sáng tỏ điều này.
Hiển thị 'blob.size' là gì? – raina77ow
blob.size nói 16892 – goh
Ok, bạn có thể đưa ra ví dụ về những gì trong 'decodedContent' không? Một giải thích là kết quả 'atob' trong chuỗi chứa các ký tự nhiều byte. Ví dụ, 'var p = atob ('ddd'); var b = new Blob ([p], {type: 'application/octet-stream'}); console.log (b.size);/* 3 */console.log (p.length);/* 2 */' – raina77ow