从ajax服务器响应获取excel文件(.xlsx)

我得到了一个问题,得到Excel文件,并在浏览器中获得该文件的响应(成功ajax方法)后打开下载窗口。 我有适当的Content-Type and Content-Disposition headers ,我尝试在js中使用Blob ,并且无法达到我想要的 – 简单的文件下载。
我完成了我的ajax的几个版本,其中之一是在下面。 我开发了AJAX,它返回的Excel文件,我无法正常打开,因为它已损坏(尽pipe.xlsx扩展名)。

也许问题是在Blob构造函数中使用不适当的数据types?

我尝试使用“xhr.response”,而不是从成功的方法参数“数据”,但它不起作用。 我在Chrome浏览器中查看了开发者工具中的响应头,并且设置正确。
重要的是 – 所有在服务器端创build的excel工作簿都是正确的,因为它在以前版本中的数据在URL中发送,而不是在ajax post中。

Java / Spring服务器端的Controller方法如下:

 response.reset(); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition","attachment;filename=\"" + className + " " + title + ".xlsx\""); try (ServletOutputStream output = response.getOutputStream()){ workbook.write(output); output.flush(); } catch (Exception e) { throw new RuntimeException(e); } 

我的Ajax下载文件并打开下载窗口:

 $.ajax({ url: myUrl, type: 'POST', data: myData, success: function(data, status, xhr) { var contentType = 'application/vnd.ms-excel'; var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, ''); } console.log("FILENAME: " + filename); try { var blob = new Blob([data], { type: contentType }); var downloadUrl = URL.createObjectURL(blob); var a = document.createElement("a"); a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); } catch (exc) { console.log("Save Blob method failed with the following exception."); console.log(exc); } 

最近我们遇到了同样的麻烦。 对于我们来说,当我们向ajax参数添加responseType: 'arraybuffer'时就开始工作了。 最好使用lib https://github.com/eligrey/FileSaver.js/而不是手动点击链接,因为这个工具也会撤销内存。

看起来JQuery在处理来自响应的二进制数据时遇到了一些问题。 我只使用XMLHttpRequest,并将所有数据添加到URL。

 var request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.responseType = 'blob'; request.onload = function(e) { if (this.status === 200) { var blob = this.response; if(window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, fileName); } else{ var downloadLink = window.document.createElement('a'); var contentTypeHeader = request.getResponseHeader("Content-Type"); downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader })); downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } }; request.send();