smartupload

 一、文件上传
1、上传页面upload.html
<!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>
   <p align="center">上传文件选择</p>
   <FORM METHOD="POST" ACTION="jsp/do_upload.jsp"ENCTYPE="multipart/form-data">
       <input type="hidden" name="TEST" value="good">
         <table width="75%" border="1" align="center">
            <tr>
              <td>
              <div align="center">
                   1.<input type="FILE" name="FILE1" size="30">
             </div>
             </td>
    </tr>
    <tr>
      <td><div align="center">2、
          <input type="FILE" name="FILE2" size="30">
        </div></td>
    </tr>
    <tr>
      <td><div align="center">3、
          <input type="FILE" name="FILE3" size="30">
        </div></td>
    </tr>
    <tr>
      <td><div align="center">4、
          <input type="FILE" name="FILE4" size="30">
        </div></td>
    </tr>
    <tr>
      <td><div align="center">
          <input type="submit" name="Submit" value="上传它!">
        </div></td>
    </tr>
  </table>
</FORM>
</body>
</html>
2、上传处理界面
<%@ page contentType="text/html; charset=gb2312" language="java"
import="java.util.*,com.jspsmart.upload.*" errorPage="" %>
<html>
<head>
<title>文件上传处理页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<%
        // 新建一个SmartUpload对象
        SmartUpload su = new SmartUpload();
        // 上传初始化
        su.initialize(pageContext);
        // 设定上传限制
        // 1.限制每个上传文件的最大长度。
        // su.setMaxFileSize(10000);
        // 2.限制总上传数据的长度。
        // su.setTotalMaxFileSize(20000);
        // 3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
        // su.setAllowedFilesList("doc,txt");
        // 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,
        jsp,htm,html扩展名的文件和没有扩展名的文件。
        // su.setDeniedFilesList("exe,bat,jsp,htm,html,,");
        // 上传文件
        su.upload();
        // 将上传文件全部保存到指定目录
        int count = su.save("/upload");
        out.println(count+"个文件上传成功!<br>");
       
        // 利用Request对象获取参数之值
        out.println("TEST="+su.getRequest().getParameter("TEST")
        +"<BR><BR>");

        // 逐一提取上传文件信息,同时可保存文件。
        for (int i=0;i<su.getFiles().getCount();i++)
        {
                com.jspsmart.upload.File file = su.getFiles().getFile(i);
               
                // 若文件不存在则继续
                if (file.isMissing()) continue;

                // 显示当前文件信息
                out.println("<TABLE BORDER=1>");
                out.println("<TR><TD>表单项名(FieldName)</TD><TD>"
                + file.getFieldName() + "</TD></TR>");
                out.println("<TR><TD>文件长度(Size)</TD><TD>" +
                file.getSize() + "</TD></TR>");
                out.println("<TR><TD>文件名(FileName)</TD><TD>"
                + file.getFileName() + "</TD></TR>");
                out.println("<TR><TD>文件扩展名(FileExt)</TD><TD>"
                + file.getFileExt() + "</TD></TR>");
                out.println("<TR><TD>文件全名(FilePathName)</TD><TD>"
                + file.getFilePathName() + "</TD></TR>");
                out.println("</TABLE><BR>");

                // 将文件另存
                // file.saveAs("/upload/" + myFile.getFileName());
                // 另存到以WEB应用程序的根目录为文件根目录的目录下
                // file.saveAs("/upload/" + myFile.getFileName(),
                su.SAVE_VIRTUAL);
                // 另存到操作系统的根目录为文件根目录的目录下
                // file.saveAs("c://temp//" + myFile.getFileName(),
                su.SAVE_PHYSICAL);

        }
%>
</body>
</html>
二、文件下载
1.下载界面
<!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/do_download.jsp">点击下载</a>
</body>
</html>
2.如何下载文件
<%@ page contentType="text/html;charset=gb2312"
import="com.jspsmart.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");
        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上传文件中文乱码 采用jspsmartupload上传文件时,如果文件名含有中文,在服务器端取得文件名是会出现乱码。如果表单项中填写了中文,一样会有乱码问题。看了下jspsmartupload的源码,改了两个地方,现在可以没有乱码问题了。 第一个地方,修改类SmartUpload中的upload()方法 // //这次用jspSmartUpload做文件上传下载, //该组件默认是GBK编码,当上传的文件名为中文时, //我将文件名getBytes()下,将GBK改成UTF-8。测试了下,貌似没问题, //突然有一次上传一文件时,发现最后几个字乱码,一直是??。在拿些文件测试, // 后来知道了是当文件名为中文奇数时,会乱码,而且还上传不了。 // 再做测试,找原因,查看字符的长度,转成16进制看结果。觉得是jspSmartUpload组件对中文支持不足的问题。 http://ru-yi86.javaeye.com/blog/368553 Java代码 1. public void upload() 2. throws SmartUploadException, IOException, ServletException 3. { 4. int totalRead = 0; 5. int readBytes = 0; 6. long totalFileSize = 0L; 7. boolean found = false; 8. String dataHeader = new String(); 9. String fieldName = new String(); 10. String fileName = new String(); 11. String fileExt = new String(); 12. String filePathName = new String(); 13. String contentType = new String(); 14. String contentDisp = new String(); 15. String typeMIME = new String(); 16. String subTypeMIME = new String(); 17. boolean isFile = false; 18. m_totalBytes = m_request.getContentLength(); 19. m_binArray = new byte[m_totalBytes]; 20. for(; totalRead < m_totalBytes; totalRead += readBytes) 21. try 22. { 23. m_request.getInputStream(); 24. readBytes = m_request.getInputStream().read(m_binArray, totalRead, m_totalBytes - totalRead); 25. } 26. catch(Exception e) 27. { 28. throw new SmartUploadException("Unable to upload."); 29. } 30. 31. for(; !found && m_currentIndex < m_totalBytes; m_currentIndex++) 32. if(m_binArray[m_currentIndex] == 13) 33. found = true; 34. else 35. m_boundary = m_boundary + (char)m_binArray[m_currentIndex]; 36. 37. if(m_currentIndex == 1) 38. return; 39. m_currentIndex++; 40. do 41. { 42. if(m_currentIndex >= m_totalBytes) 43. break; 44. dataHeader = getDataHeader(); 45. m_currentIndex = m_currentIndex + 2; 46. isFile = dataHeader.indexOf("filename") > 0; 47. fieldName = getDataFieldValue(dataHeader, "name"); 48. if(isFile) 49. { 50. filePathName = getDataFieldValue(dataHeader, "filename"); 51. fileName = getFileName(filePathName); 52. fileExt = getFileExt(fileName); 53. contentType = getContentType(dataHeader); 54. contentDisp = getContentDisp(dataHeader); 55. typeMIME = getTypeMIME(contentType); 56. subTypeMIME = getSubTypeMIME(contentType); 57. } 58. getDataSection(); 59. if(isFile && fileName.length() > 0) 60. { 61. if(m_deniedFilesList.contains(fileExt)) 62. throw new SecurityException("The extension of the file is denied to be uploaded (1015)."); 63. if(!m_allowedFilesList.isEmpty() && !m_allowedFilesList.contains(fileExt)) 64. throw new SecurityException("The extension of the file is not allowed to be uploaded (1010)."); 65. if(m_maxFileSize > (long)0 && (long)((m_endData - m_startData) + 1) > m_maxFileSize) 66. throw new SecurityException(String.valueOf((new StringBuffer("Size exceeded for this file : ")).append(fileName).append(" (1105)."))); 67. totalFileSize += (m_endData - m_startData) + 1; 68. if(m_totalMaxFileSize > (long)0 && totalFileSize > m_totalMaxFileSize) 69. throw new SecurityException("Total File Size exceeded (1110)."); 70. } 71. if(isFile) 72. { 73. com.jspsmart.upload.File newFile = new com.jspsmart.upload.File(); 74. newFile.setParent(this); 75. newFile.setFieldName(fieldName); 76. newFile.setFileName(fileName); 77. newFile.setFileExt(fileExt); 78. newFile.setFilePathName(filePathName); 79. newFile.setIsMissing(filePathName.length() == 0); 80. newFile.setContentType(contentType); 81. newFile.setContentDisp(contentDisp); 82. newFile.setTypeMIME(typeMIME); 83. newFile.setSubTypeMIME(subTypeMIME); 84. if(contentType.indexOf("application/x-macbinary") > 0) 85. m_startData = m_startData + 128; 86. newFile.setSize((m_endData - m_startData) + 1); 87. newFile.setStartData(m_startData); 88. newFile.setEndData(m_endData); 89. m_files.addFile(newFile); 90. } else 91. { 92. /** 93. * 原来的代码 94. * String value = new String(m_binArray, m_startData, (m_endData - m_startData) + 1); 95. */ 96. /** 97. * 解决取得request的参数的中文编码问题 98. */ 99. String value = new String(m_binArray, m_startData, (m_endData - m_startData) + 1, "utf-8"); 100. 101. 102. m_formRequest.putParameter(fieldName, value); 103. } 104. if((char)m_binArray[m_currentIndex + 1] == '-') 105. break; 106. m_currentIndex = m_currentIndex + 2; 107. } while(true); 108. } 第二个地方,修改类SmartUpload中的getDataHeader()方法 : Java代码 1. private String getDataHeader() 2. { 3. int start = m_currentIndex; 4. int end = 0; 5. int len = 0; 6. boolean found = false; 7. while(!found) 8. if(m_binArray[m_currentIndex] == 13 && m_binArray[m_currentIndex + 2] == 13) 9. { 10. found = true; 11. end = m_currentIndex - 1; 12. m_currentIndex = m_currentIndex + 2; 13. } else 14. { 15. m_currentIndex++; 16. } 17. 18. 19. //原始代码 20. //String dataHeader = new String(m_binArray, start, (end - start) + 1); 21. /** 22. * 解决文件名的中文乱码问题 23. */ 24. String dataHeader = null; 25. try { 26. dataHeader = new String(m_binArray, start, (end - start) + 1,"utf-8"); 27. } catch (UnsupportedEncodingException e) { 28. e.printStackTrace(); 29. } 30. return dataHeader; 31. }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值