Servlet中下载已上传的文件(已测试)
?
注:该方法下载文件,若文件不存在,但是数据库中存在文件名,则会自动创建一个空白文件给客户。
1.代码:
class="java" name="code">//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浏览器下载文件时标题为乱码!
?
?

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