AngularJS - Receive and download CSV

前端 未结 5 926
醉酒成梦
醉酒成梦 2020-12-11 17:11

I am using a nodeJS program as a server and an AngularJS web application as the client.

To create the CSV I\'m using the \"express-csv\" library (https://www.npmjs.c

5条回答
  •  余生分开走
    2020-12-11 17:17

    There are ways of downloading csv. First approach is to create a tag and click it

    Add the mimeType in below code data:application/octet-stream

    var a = document.createElement('a');
     a.href = 'data:'+mimeType+';charset=utf-8;base64,' + response;
     a.target = '_blank';
     a.download = "name the file here";
     document.body.appendChild(a);
     a.click(); 
    

    But this solution doesn't work on IE>9 and safari>6

    because safari doesn't follow download attribute for anchor tag

    so for safari you can use filesaver.js

    and IE this solution will work

    if (window.navigator.msSaveOrOpenBlob){
                    // base64 string
                    var base64str = response;
    
                    // decode base64 string, remove space for IE compatibility
                    var newstr =base64str.replace(/\s/g, '');
                    var binary = atob(newstr);
    
                    // get binary length
                    var len = binary.length;
    
                    // create ArrayBuffer with binary length
                    var buffer = new ArrayBuffer(len);
    
                    // create 8-bit Array
                    var view = new Uint8Array(buffer);
    
                    // save unicode of binary data into 8-bit Array
                    for (var i = 0; i < len; i++) {
                     view[i] = binary.charCodeAt(i);
                    }
    
                    // create the blob object with content-type "application/csv"               
                    var blob = new Blob( [view], { type: mimeType });
                    window.navigator.msSaveOrOpenBlob(blob, "Name your file here");
                }
    

提交回复
热议问题