使用组件的关联JAR包:
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
使用方式:
创建磁盘工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
设置文件缓存路径
File temp = new File(this.getServletContext().getRealPath(“/”) + “temp”) ;
factory.setReponsitory(temp) ;
创建处理工具
ServletFileUpload upload = new ServletFileUpload();
设置上传文件大小的上限,-1表示无限
upload.setSizeMax(3 * 1024 * 1024) ; //最大上传大小为3M
上传文件,并解析出所有的表单字段,包括普通字段和文件字段
接受所有的内容,以List形式存储在系统缓存中
List<FileItem> all = upload.praseRequest(request) ;
Iterator<FileItem> iter = all.iterator() ;
遍历取得
while(iter.hasNext()){
FileItem item =iter.next() ;
String fieldName =item.getFieldName() ; //取得控件名称
if(!item.isFormField()){ //判断是否是普通文本
String name = item.getName() ; //取得文件名称
String contentType =item.getContentType() ; //取得文本类型
long size =item.getSize() ; //取得文件大小
File saveFile = null ;
InputStream input = null ; //输入流
OutputStream output = null ; //输出流
//取得随机名
IpTiemStamp its = newIpTimeStamp(request.getRemoteAddr()) ;
input = item.getInputStream() ; //取得缓存中的数据
//设置文件保存路径
saveFile = new File( this.getServletContext().getRealPath(“/”)
+ ”upload” + File.separator+ its.getIpTimeRand()
+ ”.” + item.getName().split(“.”)[1]);
output = new FileOutputStream(saveFile) ;
int temp = 0 ;
byte data[] = new byte[512] ; //设置缓存大小
while((temp= input.read(data,0,512)) != -1){
output.write(data) ; //分块保存
}
//关闭数据流
input.close() ;
output.close() ;
}else{
String value = item.getString() ; //取得表单传递的值
}
}
使用情况
FileUpload控件一般使用在框架中,否则一般使用smartUpload控件完成上传功能。因为前者的使用非常复杂繁琐。