利用Jakarta commons fileupload组件实现多文件上传
首先,需要到其 官网上下载最新的jar包及其依赖的jar包,然后可以参考一下它的user guide,很简单,想信大家都能看懂,这里就把主要的内容提一下(相当于一个删减的翻译)。
一.基本原理
FileUpload组件将页面提交的所有元素(普通form表单域,如text和文件域file)都看作一样的FileItem,这样上传页面提交的request请求也就是一个FileItem的有序组合,FileUpload组件可以解析该request,并返回一个一个的FileItem。而对每一个FileItem,FileUpload组件可以判断出它是普通form表单域还是文件file域,从而根据不同的类型,采取不同的操作--如果是表单域,就读出其值,如果是文件域,就保存文件到服务器硬盘上或者内存中。
二.具体实现
对一个HttpRequest请求,我们要判断该请求是否是文件上传的请求
//
Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
如果确实是文件上传的请求,我们如何解析该request呢?
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
//
Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
//
Process a regular form field
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
...
}
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
...
}
//
Process a file upload
if ( ! item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
...
}
if ( ! item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
...
}
File uploadedFile
=
new
File(...);
item.write(uploadedFile);
item.write(uploadedFile);
在下一篇文章中,我会对commons FileUpload组件稍作包装,并做个简单的demo