Reputation: 85
I am tryig to send some data from jsp form to a servlet. All my data are type="text"
except from one that is type="file
". I know that if i want to send the data to my servlet, i have to use request.getParameter(...)
. (My data) In order not to be null i have to use method="get"
. But if i want to upload a file i have to use method="post"
. How can i pass both types to my servlet using one form? Thanks in advance!
.jsp
<form method="post" action="Servlet">
user:<input type="text" name="user"/>
img<input type="file" name="img"/>
</form>
Servlet.java
doPost(req,resp){
user = req.getParameter("user");//user == NULL
}
OR
.jsp
<form method="get" action="Servlet">
user:<input type="text"/>
img<input type="file"/>
</form>
Servlet.java
doGet(req,resp){
//img not passed
}
Upvotes: 1
Views: 1137
Reputation: 13222
Form:
<form id="uploadForm" name="uploadForm" action="UploadServlet" method="post" enctype="multipart/form-data">
user:<input type="text" name="user"/>
img<input type="file" name="image"/>
</form>
You can still get both with a post request:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
InputStream fileContent = null;
String user = "";
for (FileItem item : items)
{
if (item.isFormField())
{
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if(fieldName.equalsIgnoreCase("user"))
{
user = fieldValue;
}
}
else
{
String fieldName = item.getFieldName();
if(fieldName.equalsIgnoreCase("image"))
{
fileContent = item.getInputStream();
}
}
}
}
This is just an example of how to handle post
request with file type.
Upvotes: 1