1、
ServletFileUpload.isMultipartContent(request)
检测request中是否包含有multipart内容
2、如果有,生成DiskFileItemFactory工厂将进行相关的设置
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("d:/"));
3、生成上传ServletFileUpload类,并将DiskFileFactory工厂传给它,并对ServletFileUpload进行配置
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
4、从request得到上传的文件列表
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
5、处理文件:写入或者其他操作
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(
filePath
+ fileName.substring(fileName
.lastIndexOf("\\")));
} else {
file = new File(
filePath
+ fileName.substring(fileName
.lastIndexOf("\\") + 1));
}
fi.write(file);
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}
说明:
FileItem接口是对用户上传文件的封装
DiskFileItemFactory实现了FileItemFactory接口,主要方法有public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName)
ServletFileUpload从FileUpload继承,而FileUpload又从FileUploadBase继承,功能:分析传入的request对象、得到文件列表FileItemIterator……