实现文件下载及不同浏览器的乱码问题

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置请求编码
		request.setCharacterEncoding("utf-8");
		//获取需要下载的文件名
		String fileName = request.getParameter("fileName") ;
		System.out.println(fileName);
		//设置两个  响应头
		response.addHeader("content-Type", "application/octet-stream");
		//获取客户端的User-Agent  (判断用户用的什么浏览器)
		String browser = request.getHeader("User-Agent");
		if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
			// IE6, IE7 浏览器
			response.addHeader("content-disposition",
					"attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
		} else if (-1 < browser.indexOf("MSIE 8.0")) {
			// IE8
			response.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		} else if (-1 < browser.indexOf("MSIE 9.0")) {
			// IE9
			response.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		} else if (-1 < browser.indexOf("Chrome")) {
			// 谷歌
			response.addHeader("content-disposition",
					"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
		} else if (-1 < browser.indexOf("Safari")) {
			// 苹果
			response.addHeader("content-disposition",
					"attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
		} else {
			// 火狐或者其他的浏览器
			response.addHeader("content-disposition",
					"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
		}
//		response.addHeader("content-Disposition", "attachment;filename="+fileName);
		//Servlet通过文件的地址将文件转为输入流  读到Servlet 中
		String path = "res/"+fileName ;(我这里是绝对位置,可根据自己的需要进行修改)
		InputStream in = getServletContext().getResourceAsStream(path) ;
		//通过输出流  将刚才已转为输入流的文件输出给用户
		ServletOutputStream out = response.getOutputStream();
		byte[] bs = new  byte[1024] ;
		int len = -1 ;
		while( ( len=in.read(bs) ) != -1 ) {
			out.write(bs,0,len);;
		}
		out.close();
		in.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值