I am using a catch-all servlet and passing the request object along to other internal framework classes. Its how my application is designed. The reasons are beyond the scope of this question.
@WebServlet(name="RequestHandler", urlPatterns="/*")
I am trying to do file uploading from the browser using multipart-form-data:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" name="videoUpload" value="Upload"/>
</form>
And the only way to actually pass the file data along to the server is to annotate the servlet with:
@MultipartConfig
If I annotate my catch-all servlet, everything works fine but its not very often at all that I actually need to use the file uploading functionality.
Option 1: Leave it alone. Does leaving the annotation cause unnecessary overhead even though most of the requests don't use it?
Option 2: Add it programatically? Is there a way to programatically add the annotation if the form type of multipart is detected?
Option 3: Use the annotation elsewhere. What about using the annotation in a separate class (i'm assuming it needs to be present before the request object is actually created...)?
It is ok if you dont add '@MultipartConfig' annotation. You can determine programmatically if the content is multipart or not:
String form_field="";
FileItem fileItem = null;
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
out.print(ex);
}
String optionalFileName = "";
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("form_field")) {
form_field = fileItemTemp.getString();
}
} else {
if (fileItemTemp.getFieldName().equals("file")) {
fileItem = fileItemTemp;
}
}
}
}
If ServletFileUpload.isMultipartContent(request) is false then you can retrieve form parameters in general way by request.getParameter. I have used apache file upload in the example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.