Servlet中下载已上传的文件(已测试)

Servlet中下载已上传的文件(已测试)

 

注:该方法下载文件,若文件不存在,但是数据库中存在文件名,则会自动创建一个空白文件给客户。

注:这里只是流的传输,不在页面显示——即不获取文件中的内容!!!

(如需获取文件内容,请查看:http://zyjustin9.iteye.com/admin/blogs/2134415

1.代码:

//1.通过id在数据库中获取已存的文件的名称
PolicyDao pdao =new PolicyDao();
String sID=request.getParameter("id");
long id = Long.parseLong(sID);
String fileName = pdao.getPolicyDoc(id);//如:文件1.doc
String uploaPath = Configuration.getConfig().getString("policyFilesPath");//如:D:\logs\
try {
	File file = new File(uploaPath + fileName);//D:\logs\文件1.doc
	response.setContentType("text/plain");
	//response.setHeader("Location",fileName);//此句不要没影响
	response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("GBK"), "iso-8859-1"));//修改文件标题的编码
	//response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
	/**注意:系统是UTF-8的,但是设置为UTF-8编码时,IE下载时文件标题为乱码!其他浏览器不会!设置为GBK时都正常!*/
	OutputStream out = response.getOutputStream();
	InputStream inputStream = new FileInputStream(file);
	byte[] buffer = new byte[1024];
	int i = -1;
	while ((i = inputStream.read(buffer)) != -1) {
		out.write(buffer, 0, i);
	}
	out.flush();
	out.close();
} catch (FileNotFoundException e) {
	logger.error(e.toString());
	System.out.println("文件未找到");
}
return;

 

2.错误设置:

utf-8编码会导致IE浏览器下载文件时标题为乱码!

 

 



不设置编码时,下载的文件标题中的中文消失!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值