Download Excel file from server and save on client

别来无恙 提交于 2019-12-01 00:57:34

问题


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

回答1:


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+)



来源:https://stackoverflow.com/questions/29853359/download-excel-file-from-server-and-save-on-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!