java web应用文件下载(包括中文文件名乱码处理) .
Java web下载文件功能的确很简单。如下代码片段
Java web下载文件功能的确很简单。如下代码片段
view plaincopy to clipboardprint?
01.String fileName ="....";
02.response.setHeader("Content-disposition","attachment; filename="+fileName);
03.//response.setContentType("application/ms-word");
04.
05.BufferedInputStream bis = null;
06.BufferedOutputStream bos = null;
07. try {
08. bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("" + fileName)));
09. bos = new BufferedOutputStream(response.getOutputStream());
10.
11. byte[] buff = new byte[2048];
12. int bytesRead;
13.
14. while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
15. bos.write(buff,0,bytesRead);
16. }
17.
18. } catch(final IOException e) {
19. System.out.println ( "IOException." + e );
20.
21. } finally {
22. if (bis != null)
23. bis.close();
24. if (bos != null)
25. bos.close();
26. }
String fileName ="....";
response.setHeader("Content-disposition","attachment; filename="+fileName);
//response.setContentType("application/ms-word");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("" + fileName)));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
} catch(final IOException e) {
System.out.println ( "IOException." + e );
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
如上所示,已经可以完成下载的功能。不过如果我们使用中文文件名,那么这段代码便会出错,解决办法有多种方式,如下:
第一种: 设置 response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));这里将文件名编码成UTF-8的格式,就不会出现URL出错了。IE6下注意中文文字不能超过超过17个。
第二种:设置response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );将中文名编码为ISO8859-1的方式。不过该编码只支持简体中文.
按照上诉方式,可以综合一下两种方式解决绝大部分中文问题。
fileName = URLEncoder.encode(fileNameSrc,"UTF-8");
if(fileName.length()>150)//解决IE 6.0 bug
fileName=new String(fileNameSrc.getBytes("GBK"),"ISO-8859-1");
response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);