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浏览器下载文件时标题为乱码!
不设置编码时,下载的文件标题中的中文消失!