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

后端 未结 2 1664
再見小時候
再見小時候 2020-12-29 11:03

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,         


        
相关标签:
2条回答
  • 2020-12-29 11:44

    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

    0 讨论(0)
  • 2020-12-29 11:59

    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);
          }
    });
       

    0 讨论(0)
提交回复
热议问题