原因: Ajax 请求只是个 "字符型" 的请求, 即请求的内容是以文本类型存放的. 文件的下载是以二进制形式进行的, Ajax 没法解析后台返回的文件流, 所以无法处理二进制流 response 输出来下载文件.
解决方法: 使用 form 表单提交实现文件下载
1, 后台代码实现方法:
- // 生成 Excel 文件
- @RequestMapping(value = "/study", method = RequestMethod.POST)
- public void study(@RequestBody ParamVO paramVO, HttpServletResponse response) throws UnsupportedEncodingException {
- response.setContentType("application/octet-stream;charset=utf-8");
- response.setContentType("application/vnd.ms-excel");
- response.setHeader("Content-disposition", "attachment;filename=" + new String(paramVO.getFileName().getBytes("utf-8"), "iso-8859-1"));
- try (ByteArrayOutputStream bos = templateService.Excel(paramVO);
- BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
- out.write(bos.toByteArray());
- response.setHeader("Content-Length", String.valueOf(bos.toByteArray().length));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
2, 前端页面使用 Ajax 下载文件
- var xhr = new XMLHttpRequest();
- xhr.open('post', 'http://localhost:8080/user/export', true);
- xhr.responseType = 'blob';
- xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
- xhr.onload = function () {
- if (this.status == 200) {
- var blob = this.response;
- var a = document.createElement('a');
- var url = Windows.URL.createObjectURL(blob);
- a.href = url;
- // 设置文件名称
- a.download = '用户信息. xls';
- a.click();
- }
- }
- xhr.send(JSON.stringify({
- "type" : 1,
- "startDate" : "2018-01-01",
- "endDate" : "2018-12-31"
- }));
- }
或者前端也可以这样实现:
- {
- var xhr = new XMLHttpRequest();
- xhr.open('post', 'http://localhost:8080/user/export', true);
- xhr.responseType = 'blob';
- xhr.onload = function () {
- var blob = this.response;
- if(Windows.navigator.msSaveOrOpenBlob){
- Windows.navigator.msSaveBlob(blob, 'msSaveBlob_testFile.txt');
- }else{
- var link = document.createElement('a');
- link.href = Windows.URL.createObjectURL(blob);
- link.download = 'msSaveBlob_testFile.txt';
- link.click();
- Windows.URL.revokeObjectURL(link.href);
- }
- xhr.send(null);
- }
- }
本文转自:
来源: http://www.bubuko.com/infodetail-2987709.html