普通方式:
org.apache.commons.fileupload.disk.DiskFileItemFactory的jar包自己写的方法。
那个方法里核心是调用了
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = fileItems = upload.parseRequest(request);
示例代码:
public static String processFormData(HttpServletRequest request, Map formMap) {
String message = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String value = PropertiesUtil.getConfigureMessage("image-upload-max-size");
int imageMaxSize = Integer.parseInt(value);
int formMaxSize = 30 * 1024 * 1024;
upload.setSizeMax(formMaxSize);
List fileItems = null;
try {
fileItems = upload.parseRequest(request);
} catch (FileUploadException ex) {
message = PropertiesUtil.getErrorMessage("utilhttp.upload.oversize");
return message;
}
Iterator it = fileItems.iterator();
FileItem fileItem = null;
String fieldName = null, fileName = null;
long imgSize = 0;
it = fileItems.iterator();
while (it.hasNext()) {
fileItem = (FileItem) it.next();
fieldName = fileItem.getFieldName();
if (fileItem.isFormField()) {
formMap.put(fieldName, fileItem.getString().trim());
} else {
fileName = fileItem.getName();
// no-select file
if (fileName.trim() == "") {
continue;
}
imgSize = fileItem.getSize();
if (imgSize > 0) {
if (fileName.lastIndexOf(File.separator) > 0) {
fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
}
fileName = fileName.toLowerCase();
if (!validateFileFormats(fileName)) {
message = PropertiesUtil.getErrorMessage("utilhttp.upload.photo.type.unallowed");
return message;
} else if (imgSize > imageMaxSize) {
message = "toolarge";
return message;
}
formMap.put(fieldName, fileItem.get());
} else {
// empty image
message = "empty.image";
return message;
}
}
}
return null;
}
还有另一种方法,ofbiz里有一个HttpRequestFileUpload的工具类。它的上传文件到服务器的方法是
HttpRequestFileUpload uploadObject = new HttpRequestFileUpload();
uploadObject.setOverrideFilename(defaultFileName);
uploadObject.setSavePath(imageServerPath + "/" + filePathPrefix);
uploadObject.doUpload(request);
阅读(1434) | 评论(0) | 转发(0) |