存储数据有两种形式,数据库和文件.因此文件上传几乎是所有的应用程序开发都必须掌握的技术.目前在java领域一般也是采用第三方组件.常见的是:jspsmartupload,common_fileupload.
一,JSPSMARTUPLOAD.
jspsmart的官方网站是www.jspsmart.com.
csdn收录了一篇有关它的文章http://dev.youkuaiyun.com/develop/article/18/18987.shtm.
http://www.csdn.com.cn/program/3027.htm
写的很详细了.可以作为使用的一个参考.
二,common_fileupload
他是jakarta下属的common项目的一个子项目.
他的主要的类如下所示:
树形结构图如下:
我们在上传文件的时候,主要用到的是DiskFiluUpload类和FileItems接口.
DiskFileUpload类除了继承FileUploadBase的方法外,还加入了getFileItemFactory,setFileItemFactorygetRepositoryPath,setRepositoryPath,getSizeThresholdsetSizeThreshold,parseRequest七个方法.以下简单介绍:
setSizeThreshold(int sizeThreshold):
设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
setRepositoryPath(java.lang.String repositoryPath):
RepositoryPath 指定缓冲区目录。
parseRequest(javax.servlet.http.HttpServletRequest req, int sizeThreshold, long sizeMax, java.lang.String path):解析HttpServletRequest 返回一个FileItem列表.
setSizeMax(int size):
设置允许用户上传文件大小,单位:字节
FileItem接口的实现是DefaultFileItem.
常用的方法有:
isFormField:判断是否是普通文本域
getName:取得文件在客户机器上得名字(包括路径)
getSize :取得文件大小
getString:以字符串形式在内存中保存
write(java.io.File file):写入磁盘
下面是一个经典的例子:
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
DiskFileUpload fu = new DiskFileUpload();
// maximum size before a FileUploadException will be thrown
fu.setSizeMax(1000000);
// maximum size that will be stored in memory
fu.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
fu.setRepositoryPath("/tmp");
List fileItems = fu.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator i = fileItems.iterator();
String comment = ((FileItem)i.next()).getString();
FileItem fi = (FileItem)i.next();
// filename on the client
String fileName = fi.getName();
// save comment and filename to database
...
// write the file
fi.write("/www/uploads/" + fileName);
}
特点:
这种方法最突出的缺点就是在取普通表单域的时候十分不方便.通常的做法是
if(fi.isFormField){
fieldName =fi.getFieldName();
if( fieldName != null &&fieldName .trim().equals("fileDec")){
String fileDec = fi.getString();
}
}
要加上一堆if语句.
三,struts中利用formFile的上传,由于在方法中设计到太多的流的操作,笔者使用的比较少.可以在struts发布的例子里面找到一个教程.