Spring mvc 文件下载

本文介绍了一个用于从服务器下载文件的控制器方法。该方法接收文件路径作为参数,并通过HTTP响应将指定路径的文件返回给客户端。文章详细展示了如何设置HTTP响应头以确保正确的内容类型和编码,同时实现了文件流的读取和输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@RequestMapping(value = "/statement/downFile.action")
	public void downloadFile(@RequestParam String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {
		File reportFile = null;
		try {
			if (filePath == null || filePath.length() == 0)
				return;
			OutputStream output = response.getOutputStream();
			reportFile = new File(filePath);
			response.setCharacterEncoding("utf-8");  
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", "attachment; filename="  
	                + new String("小区统计.xls".getBytes("utf-8"), "ISO8859-1"));  
			response.setHeader("Content-Length", String.valueOf(reportFile.length()));  
			FileInputStream fis = new FileInputStream(reportFile);
			byte[] b = new byte[1024];
			int i = 0;
			while((i=fis.read(b))>0)
				output.write(b,0,i);
			output.flush();
			fis.close();
			output.close();
			
		} catch (Exception e) {
			Logger.getLogger(this.getClass().getName()).error(e);
			e.printStackTrace();
		}finally{
			if(reportFile != null)
				reportFile.delete();
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值