分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

用ajax下载字节流形式的excel文件

发布时间:2023-09-06 02:35责任编辑:林大明关键词:excel

原因: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 = window.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(window.navigator.msSaveOrOpenBlob){ ?????????window.navigator.msSaveBlob(blob, ‘msSaveBlob_testFile.txt‘); ?????}else{ ?????????var link = document.createElement(‘a‘); ?????????link.href = window.URL.createObjectURL(blob); ?????????link.download = ‘msSaveBlob_testFile.txt‘; ?????????link.click(); ?????????window.URL.revokeObjectURL(link.href); ?????} ?????xhr.send(null); ?????}}

本文转自:https://blog.csdn.net/hj7jay/article/details/86309968

用ajax下载字节流形式的excel文件

原文地址:https://www.cnblogs.com/nizuimeiabc1/p/10534415.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved