public void Parse(FileItem fi) {
if (fi.isFormField()) {
//将form中的路径参数保存为Attribute
request.setAttribute(fi.getFieldName(), fi.getString());
} else {
String path = (String) request.getAttribute(FILEPATHFIELD);
if (path != null) {
try {
String fn = path + extractfilename(fi.getName());
File f = new File(_resources.getDocBase() + fn);
if (fi.isInMemory()) {
//在内存中的直接保存到文件
fi.write(f);
} else {
//重命名速度较复制快,适合于大文件
((DiskFileItem) fi).getStoreLocation().renameTo(f);
}
_resources.lookup(fn);
} catch (Exception e) {
e.printStackTrace();
} finally {
fi.delete();//删除临时文件
}
}
}
}
public static boolean uploadfile(HttpServletRequest req) {
DiskFileItemFactory factory = null;
try {
factory = new DiskFileItemFactory();
//......
upload.setProgressListener(...);
List<?> fileItems = null;
// if fail then the Repository file can't delete
/**
* modify org.apache.commons.fileupload public List
* parseRequest(RequestContext ctx) throws FileUploadException { try
* { FileItemIterator iter = getItemIterator(ctx); List items = new
* ArrayList(); FileItemFactory fac = getFileItemFactory(); if (fac
* == null) { throw new NullPointerException(
* "No FileItemFactory has been set."); } while (iter.hasNext()) {
* FileItemStream item = iter.next(); FileItem fileItem =
* fac.createItem(item.getFieldName(), item.getContentType(),
* item.isFormField(), item.getName()); try {
* Streams.copy(item.openStream(), fileItem.getOutputStream(),
* true); } catch (FileUploadIOException e) { //here, delete
* Repository item.delete(); throw (FileUploadException)
* e.getCause(); } catch (IOException e) { //here, delete Repository
* item.delete(); throw new IOFileUploadException( "Processing of "
* + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e);
* } if (fileItem instanceof FileItemHeadersSupport) { final
* FileItemHeaders fih = item.getHeaders();
* ((FileItemHeadersSupport) fileItem).setHeaders(fih); }
* items.add(fileItem); } return items; } catch
* (FileUploadIOException e) { throw (FileUploadException)
* e.getCause(); } catch (IOException e) { throw new
* FileUploadException(e.getMessage(), e); } }
*/
fileItems = upload.parseRequest(req);
for (Object i : fileItems) {
Parse((FileItem) i);
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (factory != null) {
}
}
return false;
}