web文件上传可能是网站建设中最常用的功能之一,我在项目开发中几乎都需要实现文件上传功能.前段时间自己搜集了一些上传组件.这篇文章中将介绍这些组件的使用方法,并且比较各自的优劣.
一,smartupload组件.
我想只要做个文件上传的朋友都知道这个组件,我认识的人中使用最多的也是它!我刚到公司的时候,公司也使用的smartupload,这个组件上传相对较小的文件时是个不错的选择.下面给出个使用的例子:
<%@ page contenttype="text/html;charset=gb2312"%><%@ page import="java.sql.*"%><%@ page import="com.jspsmart.upload.*" %>
<% //实例化上载bean smartupload mysmartupload=new smartupload(); //初始化 mysmartupload.initialize(pagecontext); //设置上载的最大值,注意:如果这里设置过大会出现问题! mysmartupload.setmaxfilesize(500 * 1024*1024); //上载文件 mysmartupload.upload(); //循环取得所有上载的文件 for (int i=0;i<mysmartupload.getfiles().getcount();i++){ //取得上载的文件 com.jspsmart.upload.file myfile = mysmartupload.getfiles().getfile(i); if (!myfile.ismissing()) { //取得上载的文件的文件名 string myfilename=myfile.getfilename(); //取得不带后缀的文件名 string suffix=myfilename.substring(0,myfilename.lastindexof(.)); //取得后缀名 string ext= mysmartupload.getfiles().getfile(0).getfileext(); //取得文件的大小 int filesize=myfile.getsize(); //保存路径 string aa=getservletcontext().getrealpath("/")+"jsp\\"; string trace=aa+myfilename; //取得别的参数 string explain=(string)mysmartupload.getrequest().getparameter("text"); string send=(string)mysmartupload.getrequest().getparameter("send"); //将文件保存在服务器端 myfile.saveas(trace,mysmartupload.save_physical); %>
但是使用smartupload上传过大文件,或者多文件的时候可能出现cpu或内存占用过高的问题.并且:只有重新启动容器才能恢复正常!这正是我最后我放弃了使用smartupload的原因.
二,commons-fileupload组件
这个组件是我现在使用的组件,下载地址:http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi,包内包含了api文档.
使用该组件的例子:
<%@ page language=“java”contenttype=“text/html;charset=gbk”%><%@ page import=“java.util.*”%><%@ page import=“org.apache.commons.fileupload.*”%><html><head><title>文件上传</title></head><% diskfileupload fu = new diskfileupload(); // 设置允许用户上传文件大小,单位:字节 fu.setsizemax(10000000); // 设置最多只允许在内存中存储的数据,单位:字节 fu.setsizethreshold(4096); // 设置一旦文件大小超过getsizethreshold()的值时数据存放在硬盘的目录 fu.setrepositorypath(“d:\\tomcat5\\temp”); //开始读取上传信息 list fileitems = fu.parserequest(request); // 依次处理每个上传的文件 iterator iter = fileitems.iterator(); while (iter.hasnext()) { fileitem item = (fileitem) iter.next(); //忽略其他不是文件域的所有表单信息 if (!item.isformfield()) { string name = item.getname(); item.write(“d:\\uploadtest\\”+ name); }}%>
从上面的程序可以看出,该组件上传时候可以用了一个地方来存储临时文件,呆上传完成后直接把文件写过去.这样就不会占用过多的内存!而且该组件上传大文件的时候效率也不低哦!
在这两个的对比选择中,我选择了后者,因为我做的项目中经常上传大于10m的文件,用前者的时候服务器几乎被整崩溃.
不过,现在我已经不用这两种组件了,因为http方式传文件效率始终很低,我们现在使用的是web方式实现的ftp文件上传,我将在下篇文章中写我在项目中是如何实现的.
