I have a form. it has file uploading part as well as several input Fields. i am using request.getParameter(
) to get values from the jsp into the servlet.
But when i add encrypt=multipart
, request.get parameter doesn't work. it returns null. i know multipart does not support for the request.getParameter()
. Is there any solution for upload files. I want to use request.get parameter also.
getParameter(java.lang.String name) Returns the value of a request parameter as a String , or null if the parameter does not exist.
getParameter() method to get the value of a form parameter. getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.
multipart/form-data is often found in web application HTML Form documents and is generally used to upload files. The form-data format is the same as other multipart formats, except that each inlined piece of content has a name associated with it.
Annotate your servlet with @MultipartConfig
, then use the getParts()
method to access the parts. You are using Servlet 3.0, right?
apache commons library will be useful for such requirement.
refer: http://javakart.blogspot.in/2012/11/file-upload-example-using-servlet.html http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//this will help you identify request is of type multipart or not.
once you check, parse the request and get the form fields and File Item using library.
Example:
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
// ... (do your job here)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With