Pages

Hot News

Showing posts with label Request Parameter. Show all posts
Showing posts with label Request Parameter. Show all posts

Monday, 21 April 2014

How to get string parameter from request when using enctype="multipart/form-data" ?

Hi guys,

Descriptions:

When [ <form> tag ] which has enctype="multipart/form-data"  and also contain additional input type="text" with name="username" and a submit button.

jsp:

<form action="upload" method="post" enctype="multipart/form-data">
User Name: <input type="text" name="username" /><br/>
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>

retrieve string paramName as:
String username = request.getParameter("username"); 
That's prints NULL when form has enctype="multipart/form-data"  If I remove this attributes from the form tag then prints value input by user. 


Whenever a form has enctype="multipart/form-data" . You can not get other form fields by using request.getParameter("paramName");
It will always give you NULL value.

*This problem can be resolved by using below way.

Write the below code in your servlet and get the values of additional formfields :

   List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
   String inputName = null;
for(FileItem item : multiparts){
if(!item.isFormField()){   // Check regular field.
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIR + File.separator + name));
}
if(item.isFormField()){  // Check regular field.
inputName = (String)item.getFieldName(); 
if(inputName.equalsIgnoreCase("username")){ 
username = (String)item.getString(); 
        System.out.println("UserName is:"+username); 
}
}
}

That's All !!
Let me know if u have any suggestions/queries, I would like to hear from your side.