
jspSmartUpload上传下载全攻略 [转](7) |
public void downloadFile(String s, String s1, String s2, int i) throws ServletException, IOException, SmartUploadException { if(s == null) throw new IllegalArgumentException("File " + s + " not found (1040)." ;if(s.equals("" )throw new IllegalArgumentException("File " + s + " not found (1040)." ;if(!isVirtual(s) && m_denyPhysicalPath) throw new SecurityException("Physical path is denied (1035)." ;if(isVirtual(s)) s = m_application.getRealPath(s); java.io.File file = new java.io.File(s); FileInputStream fileinputstream = new FileInputStream(file); long l = file.length(); boolean flag = false; int k = 0; byte abyte0[] = new byte[i]; if(s1 == null) m_response.setContentType("application/x-msdownload" ;else if(s1.length() == 0) m_response.setContentType("application/x-msdownload" ;else m_response.setContentType(s1); m_response.setContentLength((int)l); m_contentDisposition = m_contentDisposition != null ? m_contentDisposition : "attachment;"; if(s2 == null) m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + toUtf8String(getFileName(s))); else if(s2.length() == 0) m_response.setHeader("Content-Disposition", m_contentDisposition); else m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + toUtf8String(s2)); while((long)k < l) { int j = fileinputstream.read(abyte0, 0, i); k += j; m_response.getOutputStream().write(abyte0, 0, j); } fileinputstream.close(); } /** * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名. * 纵横软件制作中心雨亦奇2003.08.01 * @param s 原文件名 * @return 重新编码后的文件名 */ public static String toUtf8String(String s) { StringBuffer sb = new StringBuffer(); for (int i=0;i<s.length();i++) { char c = s.charAt(i); if (c >= 0 && c <= 255) { sb.append(c); } else { byte[] b; try { b = Character.toString(c).getBytes("utf-8" ;} catch (Exception ex) { System.out.println(ex); b = new byte[0]; } for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) k += 256; sb.append("%" + Integer.toHexString(k). toUpperCase()); } } } return sb.toString(); } 注意源码中粗体部分,原jspSmartUpload组件对返回的文件未作任何处理,现在做了编码的转换工作,将文件名转换为UTF-8形式的编码形式。UTF-8编码对英文未作任何处理,对中文则需要转换为%XX的形式。toUtf8String方法中,直接利用Java语言提供的编码转换方法获得汉字字符的UTF-8编码,之后将其转换为%XX的形式。 将源码编译后打包成jspSmartUpload.jar,拷贝到Tomcat的shared/lib目录下(可为所有WEB应用程序所共享),然后重启Tomcat服务器就可以正常下载含有中文名字的文件了。另,toUtf8String方法也可用于转换含有中文的超级链接,以保证链接的有效,因为有的WEB服务器不支持中文链接。 小结:jspSmartUpload组件是应用JSP进行B/S程序开发过程中经常使用的上传下载组件,它使用简单,方便。现在我又为其加上了下载中文名字的文件的支持,真个是如虎添翼,必将赢得更多开发者的青睐。 |