四、文件下載篇
1、下載鏈接頁面download.html
頁面源碼如下:
<!--文件名:download.html作 者:縱橫軟件制作中心雨亦奇([email protected])--><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>下載</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body><a href="jsp(SUN企業級應用的首選)/do_download.jsp(SUN企業級應用的首選)">點擊下載</a></body></html>
<%@ page contentType="text/html;charset=gb2312" import="com.jsp(SUN企業級應用的首選)smart.upload.*" %><%// 新建一個SmartUpload對象SmartUpload su = new SmartUpload();// 初始化su.initialize(pageContext);// 設定contentDisposition為null以禁止浏覽器自動打開文件,//保證點擊鏈接後是下載文件。若不設定,則下載的文件擴展名為//doc時,浏覽器將自動用word打開它。擴展名為pdf時,//浏覽器將用acrobat打開。su.setContentDisposition(null);// 下載文件su.downloadFile("/upload/如何賺取我的第一桶金.doc");%>
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");elseif(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)));elseif(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(); }