采用hutool后端返回文件流供前端下载

1、导入依赖

<!--hutool-->
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.7.20</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.1.2</version>
		</dependency>

2、代码

import java.net.URLDecoder;
import org.apache.commons.io.IOUtils;


    /**
     * 下载房源信息导入模板
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    public void downLoadPropertyExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String fileName = "房源信息导入模板.xlsx";
        fileName = URLDecoder.decode(fileName, "UTF-8");
        InputStream in = this.getClass().getResourceAsStream("/template/房源信息导入模板.xlsx");
        String filenamedisplay = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filenamedisplay);
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream out = response.getOutputStream();
        IOUtils.copy(in, out);
        out.flush();
        in.close();
    }

3、前端测试

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<!-- 以下两种方式都可 -->
		<button id="downLoad">下载</button>
		<a href="http://127.0.0.1:8055/yxroom/directSeeding/downLoadBuyerExcel">点击下载文件</a>
		
	</body>
	<script>
		document.getElementById('downLoad').onclick = function(){
			alert("开始下载");
			// window.location.href = 'http://127.0.0.1:8055/yxroom/directSeeding/downLoadPropertyExcel';
			window.location.href = 'http://127.0.0.1:8055/yxroom/directSeeding/downLoadBuyerExcel';
		}
	</script>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值