文件下载-java

public static void downLoadFile(HttpServletRequest request,HttpServletResponse response,String fullPath) throws IOException {
		OutputStream outp = response.getOutputStream();
		File file = new File(fullPath);
		if (file.exists()) {
			//设置请求以及响应的内容类型以及编码方式
			response.setContentType("application/x-msdownload; charset=utf-8"); 
			String agent = (String)request.getHeader("USER-AGENT");  
			
			if (agent != null &&agent.toLowerCase().indexOf("firefox") > 0)  {
				response.setHeader("Content-Disposition", "attachment; filename=" +  new String(filename.getBytes("UTF-8"), "ISO8859-1"));//firefox浏览器  
			}else {
				//if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)  
				response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename, "UTF-8"));//IE浏览器
			}
			FileInputStream in = null;
			try {
				outp = response.getOutputStream();
				//获取文件输入流
				in = new FileInputStream(fullPath);
				byte[] b = new byte[1024];
				int i = 0;
				//将缓冲区的数据输出到客户浏览器
				while ((i = in.read(b)) > 0) {
					outp.write(b, 0, i);
				}
				outp.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					in.close();
					in = null;
				}
				if (outp != null) {
					outp.close();
					outp = null;
					response.flushBuffer();
				}
			}
		} else {
			outp.write("文件不存在!".getBytes("utf-8"));
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值