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

二次信任 提交于 2019-11-29 03:34:31

问题


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?


回答1:


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




回答2:


Building on Jepzen's response, I was able to use this technique to download a document from AWS S3 from within the browser. +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);
      }
});
   


来源:https://stackoverflow.com/questions/27946228/file-download-a-byte-array-as-a-file-in-javascript-extjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!