SpringMVC实现文件下载功能(文件导出功能)

1.页面代码

<a class="layui-btn" href="${pageContext.request.contextPath}/bAndWListManage/downloadWhiteListTmp.do" onclick="downloadTemplate();">模板下载</a>

2.后台代码

@RequestMapping("downloadWhiteListTmp")  
    public ResponseEntity<byte[]> downloadWhiteListTmp(HttpServletRequest request) {  
    	
        HttpHeaders headers = new HttpHeaders();
        String fileName="importVehicleWhitelist.xls";
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/bwlmm/templateFiles/"+fileName); 
        File file = new File(realPath);
        InputStream in;
        byte[] body=null;
        ResponseEntity<byte[]> response =null;
		try {
			in = new FileInputStream(new File(realPath));
		        body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
		        in.read(body);//读入到输入流里面
		       fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
		       headers.add("Content-Disposition", "attachment;filename="+fileName);
		       HttpStatus statusCode = HttpStatus.OK;//设置响应吗
		       response =new ResponseEntity<byte[]>(body, headers, statusCode);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}//将该文件加入到输入流之中
		catch (IOException e) {
			e.printStackTrace();
		}
       return response;
    }

3.说明

我的文件路径

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值