`
jessen163
  • 浏览: 457834 次
  • 性别: Icon_minigender_1
  • 来自: 潘多拉
社区版块
存档分类
最新评论

jspSmartUpload上传下载全攻略

    博客分类:
  • Util
阅读更多
一、安装篇

  jspsmartupload是由www.jspsmart.com网站开发的一个可免费使用的全功能的文件上传下载组件,适于嵌入执行上传下载操作的jsp文件中。该组件有以下几个特点:

1、使用简单。在jsp文件中仅仅书写三五行java代码就可以搞定文件的上传或下载,方便。

2、能全程控制上传。利用jspsmartupload组件提供的对象及其操作方法,可以获得全部上传文件的信息(包括文件名,大小,类型,扩展名,文件数据等),方便存取。

3、能对上传的文件在大小、类型等方面做出限制。如此可以滤掉不符合要求的文件。

4、下载灵活。仅写两行代码,就能把web服务器变成文件服务器。不管文件在web服务器的目录下或在其它任何目录下,都可以利用jspsmartupload进行下载。

5、能将文件上传到数据库中,也能将数据库中的数据下载下来。这种功能针对的是mysql数据库,因为不具有通用性,所以本文不准备举例介绍这种用法。

  jspsmartupload组件可以从www.jspsmart.com网站上自由下载,压缩包的名字是jspsmartupload.zip。下载后,用winzip或winrar将其解压到tomcat的webapps目录下(本文以tomcat服务器为例进行介绍)。解压后,将webapps/jspsmartupload目录下的子目录web-inf名字改为全大写的web-inf,这样一改jspsmartupload类才能使用。因为tomcat对文件名大小写敏感,它要求web应用程序相关的类所在目录为web-inf,且必须是大写。接着重新启动tomcat,这样就可以在jsp文件中使用jspsmartupload组件了。

  注意,按上述方法安装后,只有webapps/jspsmartupload目录下的程序可以使用jspsmartupload组件,如果想让tomcat服务器的所有web应用程序都能用它,必须做如下工作:

1.进入命令行状态,将目录切换到tomcat的webapps/jspsmartupload/web-inf目录下。

2.运行jar打包命令:jar cvf jspsmartupload.jar com

(也可以打开资源管理器,切换到当前目录,用winzip将com目录下的所有文件压缩成jspsmartupload.zip,然后将jspsmartupload.zip换名为jspsmartupload.jar文件即可。)

3.将jspsmartupload.jar拷贝到tomcat的shared/lib目录下。

二、相关类说明篇

㈠ file类

  这个类包装了一个上传文件的所有信息。通过它,可以得到上传文件的文件名、文件大小、扩展名、文件数据等信息。

  file类主要提供以下方法:

1、saveas作用:将文件换名另存。

原型:

public void saveas(java.lang.string destfilepathname)



public void saveas(java.lang.string destfilepathname, int optionsaveas)

其中,destfilepathname是另存的文件名,optionsaveas是另存的选项,该选项有三个值,分别是saveas_physical,saveas_virtual,saveas_auto。saveas_physical表明以操作系统的根目录为文件根目录另存文件,saveas_virtual表明以web应用程序的根目录为文件根目录另存文件,saveas_auto则表示让组件决定,当web应用程序的根目录存在另存文件的目录时,它会选择saveas_virtual,否则会选择saveas_physical。

例如,saveas("/upload/sample.zip",saveas_physical)执行后若web服务器安装在c盘,则另存的文件名实际是c:\upload\sample.zip。而saveas("/upload/sample.zip",saveas_virtual)执行后若web应用程序的根目录是webapps/jspsmartupload,则另存的文件名实际是webapps/jspsmartupload/upload/sample.zip。saveas("/upload/sample.zip",saveas_auto)执行时若web应用程序根目录下存在upload目录,则其效果同saveas("/upload/sample.zip",saveas_virtual),否则同saveas("/upload/sample.zip",saveas_physical)。

建议:对于web程序的开发来说,最好使用saveas_virtual,以便移植。

2、ismissing

作用:这个方法用于判断用户是否选择了文件,也即对应的表单项是否有值。选择了文件时,它返回false。未选文件时,它返回true。

原型:public boolean ismissing()

3、getfieldname

作用:取html表单中对应于此上传文件的表单项的名字。

原型:public string getfieldname()

4、getfilename

作用:取文件名(不含目录信息)

原型:public string getfilename()

5、getfilepathname

作用:取文件全名(带目录)

原型:public string getfilepathname

6、getfileext

作用:取文件扩展名(后缀)

原型:public string getfileext()

7、getsize

作用:取文件长度(以字节计)

原型:public int getsize()

8、getbinarydata

作用:取文件数据中指定位移处的一个字节,用于检测文件等处理。

原型:public byte getbinarydata(int index)。其中,index表示位移,其值在0到getsize()-1之间。

㈡ files类

  这个类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息。有以下方法:

1、getcount

作用:取得上传文件的数目。

原型:public int getcount()

2、getfile

作用:取得指定位移处的文件对象file(这是com.jspsmart.upload.file,不是java.io.file,注意区分)。

原型:public file getfile(int index)。其中,index为指定位移,其值在0到getcount()-1之间。

3、getsize

作用:取得上传文件的总长度,可用于限制一次性上传的数据量大小。

原型:public long getsize()

4、getcollection

作用:将所有上传文件对象以collection的形式返回,以便其它应用程序引用,浏览上传文件信息。

原型:public collection getcollection()

5、getenumeration

作用:将所有上传文件对象以enumeration(枚举)的形式返回,以便其它应用程序浏览上传文件信息。

原型:public enumeration getenumeration()

㈢ request类

  这个类的功能等同于jsp内置的对象request。只所以提供这个类,是因为对于文件上传表单,通过request对象无法获得表单项的值,必须通过jspsmartupload组件提供的request对象来获取。该类提供如下方法:

1、getparameter

作用:获取指定参数之值。当参数不存在时,返回值为null。

原型:public string getparameter(string name)。其中,name为参数的名字。

2、getparametervalues

作用:当一个参数可以有多个值时,用此方法来取其值。它返回的是一个字符串数组。当参数不存在时,返回值为null。

原型:public string[] getparametervalues(string name)。其中,name为参数的名字。

3、getparameternames

作用:取得request对象中所有参数的名字,用于遍历所有参数。它返回的是一个枚举型的对象。

原型:public enumeration getparameternames()

㈣ smartupload类这个类完成上传下载工作。

a.上传与下载共用的方法:

只有一个:initialize。

作用:执行上传下载的初始化工作,必须第一个执行。

原型:有多个,主要使用下面这个:

public final void initialize(javax.servlet.jsp.pagecontext pagecontext)

其中,pagecontext为jsp页面内置对象(页面上下文)。

b.上传文件使用的方法:

1、upload

作用:上传文件数据。对于上传操作,第一步执行initialize方法,第二步就要执行这个方法。

原型:public void upload()

2、save

作用:将全部上传文件保存到指定目录下,并返回保存的文件个数。

原型:public int save(string destpathname)

和public int save(string destpathname,int option)

其中,destpathname为文件保存目录,option为保存选项,它有三个值,分别是save_physical,save_virtual和save_auto。(同file类的saveas方法的选项之值类似)save_physical指示组件将文件保存到以操作系统根目录为文件根目录的目录下,save_virtual指示组件将文件保存到以web应用程序根目录为文件根目录的目录下,而save_auto则表示由组件自动选择。

注:save(destpathname)作用等同于save(destpathname,save_auto)。

3、getsize

作用:取上传文件数据的总长度

原型:public int getsize()

4、getfiles

作用:取全部上传文件,以files对象形式返回,可以利用files类的操作方法来获得上传文件的数目等信息。

原型:public files getfiles()

5、getrequest

作用:取得request对象,以便由此对象获得上传表单参数之值。

原型:public request getrequest()

6、setallowedfileslist

作用:设定允许上传带有指定扩展名的文件,当上传过程中有文件名不允许时,组件将抛出异常。

原型:public void setallowedfileslist(string allowedfileslist)

其中,allowedfileslist为允许上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想允许上传那些没有扩展名的文件,可以用两个逗号表示。例如:setallowedfileslist("doc,txt,,")将允许上传带doc和txt扩展名的文件以及没有扩展名的文件。

7、setdeniedfileslist

作用:用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制,则上传时组件将抛出异常。

原型:public void setdeniedfileslist(string deniedfileslist)

其中,deniedfileslist为禁止上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想禁止上传那些没有扩展名的文件,可以用两个逗号来表示。例如:setdeniedfileslist("exe,bat,,")将禁止上传带exe和bat扩展名的文件以及没有扩展名的文件。

8、setmaxfilesize

作用:设定每个文件允许上传的最大长度。

原型:public void setmaxfilesize(long maxfilesize)

其中,maxfilesize为为每个文件允许上传的最大长度,当文件超出此长度时,将不被上传。

9、settotalmaxfilesize

作用:设定允许上传的文件的总长度,用于限制一次性上传的数据量大小。

原型:public void settotalmaxfilesize(long totalmaxfilesize)

其中,totalmaxfilesize为允许上传的文件的总长度。

c.下载文件常用的方法

1、setcontentdisposition

作用:将数据追加到mime文件头的content-disposition域。jspsmartupload组件会在返回下载的信息时自动填写mime文件头的content-disposition域,如果用户需要添加额外信息,请用此方法。

原型:public void setcontentdisposition(string contentdisposition)

其中,contentdisposition为要添加的数据。如果contentdisposition为null,则组件将自动添加"attachment;",以表明将下载的文件作为附件,结果是ie浏览器将会提示另存文件,而不是自动打开这个文件(ie浏览器一般根据下载的文件扩展名决定执行什么操作,扩展名为doc的将用word程序打开,扩展名为pdf的将用acrobat程序打开,等等)。

2、downloadfile

作用:下载文件。

原型:共有以下三个原型可用,第一个最常用,后两个用于特殊情况下的文件下载(如更改内容类型,更改另存的文件名)。

① public void downloadfile(string sourcefilepathname)

其中,sourcefilepathname为要下载的文件名(带目录的文件全名)

② public void downloadfile(string sourcefilepathname,string contenttype)

其中,sourcefilepathname为要下载的文件名(带目录的文件全名),contenttype为内容类型(mime格式的文件类型信息,可被浏览器识别)。

③ public void downloadfile(string sourcefilepathname,string contenttype,string destfilename)

其中,sourcefilepathname为要下载的文件名(带目录的文件全名),contenttype为内容类型(mime格式的文件类型信息,可被浏览器识别),destfilename为下载后默认的另存文件名。


三、文件上传篇

㈠ 表单要求

对于上传文件的form表单,有两个要求:

1、method应用post,即method="post"。

2、增加属性:enctype="multipart/form-data"

下面是一个用于上传文件的form表单的例子:

<form method="post" enctype="multipart/form-data"  action="/jspsmartupload/upload.jsp">
       <input type="file" name="myfile">
        <input type="submit">
</form>

㈡ 上传的例子

1、上传页面upload.html

本页面提供表单,让用户选择要上传的文件,点击"上传"按钮执行上传操作。

页面源码如下:

<!--
    文件名:upload.html
    作  者:纵横软件制作中心雨亦奇(zhsoft88@sohu.com)
-->
<!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>&nbsp;</p>
<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、上传处理页面do_upload.jsp

本页面执行文件上传操作。页面源码中详细介绍了上传方法的用法,在此不赘述了。

页面源码如下:
<%--
    文件名:do_upload.jsp
    作  者:纵横软件制作中心雨亦奇(zhsoft88@sohu.com)
--%>
<%@ 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、下载链接页面download.html

页面源码如下:
<!--
        文件名:download.html
    作  者:纵横软件制作中心雨亦奇(zhsoft88@sohu.com)
-->
<!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、下载处理页面do_download.jsp do_download.jsp展示了如何利用jspsmartupload组件来下载文件,从下面的源码中就可以看到,下载何其简单。
<%@ 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");
%>

    注意,执行下载的页面,在java脚本范围外(即<% ... %>之外),不要包含html代码、空格、回车或换行等字符,有的话将不能正确下载。不信的话,可以在上述源码中%><%之间加入一个换行符,再下载一下,保证出错。因为它影响了返回给浏览器的数据流,导致解析出错。

3、如何下载中文文件

    jspsmartupload虽然能下载文件,但对中文支持不足。若下载的文件名中有汉字,则浏览器在提示另存的文件名时,显示的是一堆乱码,很扫人兴。上面的例子就是这样。(这个问题也是众多下载组件所存在的问题,很少有人解决,搜索不到相关资料,可叹!)

    为了给jspsmartupload组件增加下载中文文件的支持,我对该组件进行了研究,发现对返回给浏览器的另存文件名进行utf-8编码后,浏览器便能正确显示中文名字了。这是一个令人高兴的发现。于是我对jspsmartupload组件的smartupload类做了升级处理,增加了toutf8string这个方法,改动部分源码如下:
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程序开发过程中经常使用的上传下载组件,它使用简单,方便。现在我又为其加上了下载中文名字的文件的支持,真个是如虎添翼,必将赢得更多开发者的青睐。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics