Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download Excel file from server and save on client

I have a JavaScript app and an API that creates a Excel file and returns a byte array with the following headers:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Content-Disposition:attachment; filename=List.xlsx

When I go the Excel resource API URL I'm prompted to download the Excel file. If I do so, it downloads fine and opens in Excel. All is good.

Now to the problem:

What I don't want is to expose the API URL in the user's browser window, so my goal is to:

  • Download the Excel file via AJAX XMLHttpRequest
  • Store the contents (byte array) in a Blob
  • Create a data URI with the Blob
  • Open the data URI in a popup, that prompts the user to download the Excel file

What I have is this:

It downloads the file, but when I try to open the file, Excel doesn't recognize it as a valid Excel file.

// "data" is the contents from the server

var reader = new FileReader();
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
reader.readAsDataURL(blob);

reader.onloadend = function (e) {
    window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}
like image 319
Gaui Avatar asked Apr 24 '15 17:04

Gaui


1 Answers

I got it working. I just had to add the following to my XMLHttpRequest object:

responseType: 'arraybuffer'

But it doesn't work in IE, because IE cannot open data URIs. Not even IE11.

Anyway I found a great library called FileSaver.js which handles saving files for all major browsers (including IE10+)

like image 85
Gaui Avatar answered Sep 21 '22 16:09

Gaui