2015-01-14 15 views
11

Trong giải pháp Ext Js tôi tôi kêu gọi một dịch vụ mà đang trở lại định dạng JSON nàytập tin tải về một mảng byte như là một tập tin trong javascript/ExtJS

{"success":true,"filename":"spreadsheet.xlsx","file":[80,75,3,4,20,0,...(many more)]} 

Làm thế nào tôi có thể làm cho một hộp thoại tập tin tải về với tên tập tin và nội dung của mảng byte (tệp)?

CẬP NHẬT

Vì vậy, tôi tìm thấy chút này để bắt đầu downlaod

var a = window.document.createElement('a'); 
        a.href = window.URL.createObjectURL(new Blob(data.file, { type: 'application/octet-stream' })); 
        a.download = data.filename; 

        // Append anchor to body. 
        document.body.appendChild(a) 
        a.click(); 

        // Remove anchor from body 
        document.body.removeChild(a) 

Cho đến nay tốt

Nhưng những tập tin tôi nhận được là hỏng vì vậy tôi nghi ngờ tôi cần phải mã hóa/giải mã tập tin biến?

+0

Có một cái nhìn: http://stackoverflow.com/questions/1801076/renaming-files-when-downloading-it/16993368#16993368 –

Trả lời

22

tôi phải chuyển đổi các tập tin vào một Uint8Array trước khi đi qua nó vào Blob

var arr = data.file; 
var byteArray = new Uint8Array(arr); 
var a = window.document.createElement('a'); 

a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' })); 
a.download = data.filename; 

// Append anchor to body. 
document.body.appendChild(a) 
a.click(); 


// Remove anchor from body 
document.body.removeChild(a) 

Đọc câu trả lời này đã giúp rất nhiều https://stackoverflow.com/a/16245768/1016439

+0

Tôi đã dành khá nhiều thời gian trên điều này với mã hóa sai. Cảm ơn các giải pháp. Tôi đã sử dụng Uint16Array – Reddy

0

Xây dựng ứng phó Jepzen, tôi đã có thể sử dụng kỹ thuật này để tải xuống tài liệu từ AWS S3 từ trong trình duyệt. 1 Jepzen

s3.getObject(params, function(err, data) { 
 
     if (err === null) { 
 
     var arr = data.Body; 
 
     var byteArray = new Uint8Array(arr); 
 
     var a = window.document.createElement('a'); 
 

 
     a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' })); 
 
     a.download = fName; //fName was the file name portion of the key what was passed in as part of the key value within params. 
 

 
     // Append anchor to body. 
 
     document.body.appendChild(a) 
 
     a.click(); 
 

 
     // Remove anchor from body 
 
     document.body.removeChild(a) 
 
     } else { 
 
     result = 'failure' 
 
     console.log("Failed to retrieve an object: " + err); 
 
     } 
 
}); 
 

Các vấn đề liên quan