使用Servlet实现浏览器从服务器下载文件

使用Servlet实现浏览器从服务器下载文件,并包含处理中文文件名的乱码问题

 文件在Web过程中的位置信息:


Servlet实现下载文件的代码:

protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException
{
	//获取下载的文件在服务上的路径
	String path = this.getServletContext().getRealPath(
			"/download/测试中文下载.png");
	
	//获取下载的文件名
	String fileName = path.substring(path.lastIndexOf("\\") + 1);
	
	//设置浏览器以下载的方式打开数据
	response.setHeader("content-disposition", "attachment;filename=" 
			+ URLEncoder.encode(fileName, "UTF-8")); //注意:含有中文的文件名 需要给URL编码
	
	//读取图片数据并响应给客户端
	OutputStream out = response.getOutputStream();
	InputStream in = null;
	try
	{
		in = new FileInputStream(path);
		byte[] buff = new byte[1024];
		int len = 0;
		while((len = in.read(buff)) > 0)
		{
			out.write(buff, 0, len);
		}
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
	
	//由于response对象由web服务器创建,在本次请求结束后服务器会自动销毁该对象 所以不需要手动管理out流
	if(in != null)
	{
		in.close();
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值