Created
July 18, 2013 23:28
-
-
Save webdeveloper987/6033959 to your computer and use it in GitHub Desktop.
FileUpload_servlet (only part)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Validate file. | |
Object fileObject = request.getAttribute("file"); | |
if (fileObject == null) { | |
// No file uploaded. | |
myForm.setError("file", "Please select file to upload."); | |
} | |
private void processFileField(FileItem fileField, HttpServletRequest request) | |
{ | |
if (fileField.getName().length() <= 0) | |
{ | |
// No file uploaded. | |
request.setAttribute(fileField.getFieldName(), null); | |
} | |
else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) | |
{ | |
// File size exceeds maximum file size. | |
request.setAttribute(fileField.getFieldName(), new FileUploadException( | |
"File size exceeds maximum file size of " + maxFileSize + " bytes.")); | |
// Immediately delete temporary file to free up memory and/or disk space. | |
fileField.delete(); | |
} | |
else { | |
// File uploaded with good size. | |
request.setAttribute(fileField.getFieldName(), fileField); | |
} | |
} | |
//--------------------------------- | |
// Prepare the multipart request items. | |
// I'd rather call the "FileItem" class "MultipartItem" instead or so. What a stupid name ;) | |
List<FileItem> multipartItems = null; | |
try { | |
// Parse the multipart request items. | |
multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); | |
// Note: we could use ServletFileUpload#setFileSizeMax() here, but that would throw a | |
// FileUploadException immediately without processing the other fields. So we're | |
// checking the file size only if the items are already parsed. See processFileField(). | |
} catch (FileUploadException e) { | |
throw new ServletException("Cannot parse multipart request: " + e.getMessage()); | |
} | |
// Prepare the request parameter map. | |
Map<String, String[]> parameterMap = new HashMap<String, String[]>(); | |
// Loop through multipart request items. | |
for (FileItem multipartItem : multipartItems) { | |
if (multipartItem.isFormField()) { | |
// Process regular form field (input type="text|radio|checkbox|etc", select, etc). | |
processFormField(multipartItem, parameterMap); | |
} else { | |
// Process form file field (input type="file"). | |
processFileField(multipartItem, request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment