Java web下载文件功能的确很简单。如下代码片段
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);