Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File download a byte array as a file in javascript / Extjs

In my Ext Js solution I am calling a service which is returning this JSON format

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

How can I make a file download dialog with the filename and the content of the byte array (file) ?

UPDATE

So I found this bit to start the 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)

So far good

But the file I get is corrupted so I suspect I need to Encode/Decode the file variable?

like image 919
Jepzen Avatar asked Jan 14 '15 15:01

Jepzen


1 Answers

I had to convert the file into a Uint8Array before passing it to the 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)

Reading this answer helped a lot https://stackoverflow.com/a/16245768/1016439

like image 199
Jepzen Avatar answered Sep 19 '22 01:09

Jepzen