AngularJS $http-post – convert binary to excel file and download

Just noticed you can’t use it because of IE8/9 but I’ll push submit anyway… maybe someone finds it useful

This can actually be done through the browser, using blob. Notice the responseType and the code in the success promise.

    url: 'your/webservice',
    method: "POST",
    data: json, //this is your json data string
    headers: {
       'Content-type': 'application/json'
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    var objectUrl = URL.createObjectURL(blob);;
}).error(function (data, status, headers, config) {
    //upload failed

There are some problems with it though like:

  1. It doesn’t support IE 8 and 9:
  2. It opens a pop up window to open the objectUrl which people might have blocked
  3. Generates weird filenames

It did work!

The server side code in PHP I tested this with looks like this. I’m sure you can set similar headers in Java:

$file = "file.xlsx";
header('Content-disposition: attachment; filename=".$file);
header("Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo json_encode(readfile($file));

Edit 20.04.2016

Browsers are making it harder to save data this way. One good option is to use filesaver.js. It provides a cross browser implementation for saveAs, and it should replace some of the code in the success promise above.

Leave a Comment