欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot中下载模板功能

程序员文章站 2022-04-09 09:21:36
...

前台:

<button type="button" onclick="downloadMould()" style="float: right;margin-right: 20px;" class="btn btn-info">模板下载</button>

js:

function downloadMould(){
	alert("下载模板");
	window.open( "./addRepairDevice/downloadExcel");//跳转后台的路径
}

后台方法:

@RequestMapping(value = "/downloadExcel")
	@ResponseBody
	public void downloadExcel(HttpServletResponse res, HttpServletRequest req) throws Exception {
	   String fileName = "repairDeviceModel.xls";
	ServletOutputStream out;
	res.setContentType("multipart/form-data");
	res.setCharacterEncoding("UTF-8");
	res.setContentType("text/html");
	String filePath = getClass().getResource("/static/doc/" + fileName).getPath();//文件在项目中的存放路径
	String userAgent = req.getHeader("User-Agent");
	if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
	fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
	} else {
	// 非IE浏览器的处理:
		fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
	}
	filePath = URLDecoder.decode(filePath, "UTF-8");
	res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
	FileInputStream inputStream = new FileInputStream(filePath);
	out = res.getOutputStream();
	int b = 0;
	byte[] buffer = new byte[1024];
	while ((b = inputStream.read(buffer)) != -1) {
	// 4.写到输出流(out)中
	out.write(buffer, 0, b);
	}
	inputStream.close();

	if (out != null) {
	out.flush();
	out.close();
	}

	}
相关标签: 下载