0

The HTTP response for a POST request that I am getting from server side is a xlsx file.How do I download the file in angularjs 1?

Note: res.download() won't work here,since its a POST request that I am making,and res.download() works only for GET request

Ayan
  • 8,192
  • 4
  • 46
  • 51
  • Refer to this answer here https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link#19328891 – Slytherin May 25 '17 at 14:52
  • duplicate question https://stackoverflow.com/questions/31134961/downloading-excel-file-xlsx-in-angularjs-and-webapi – Kasiriveni May 25 '17 at 14:52

2 Answers2

1

The following shall work :

$http.post("url_here", post_data_to_send, {responseType: 'arraybuffer'})

     .success(function (data,status,headers) {

                var blob = new Blob([data]);
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display:none";
                a.href = objectUrl;
                a.download = headers().filename;
                a.click();                        
                console.log("Report downloaded");

                }).error(function (err) {

                    console.log(err);

                });
Ayan
  • 8,192
  • 4
  • 46
  • 51
0

You can do it directly on Client Side, you may have some cross-browser compatibility issues (the best way is always to provide a download stream via server, for large files for example).

// this example uses a JSON String 
// but you can do it with any valid blob argument
const fileContent = [JSON.stringify(
  ['something', 'to', 'download'], null, 2
)];

const downloader = document.createElement('a');

// set the filename here
downloader.download = 'filename.json';

const blob = new Blob(fileContent, {type: 'text/plain'});
downloader.href = window.URL.createObjectURL(blob);


// trigger the download
downloader.click();

In my opinion, a redirect to the downloadable resource could be the best choice.

Hitmands
  • 13,491
  • 4
  • 34
  • 69