I have a java upload servlet and jsp form. the upload portion is working fine but i cannot get the regular form values in the upload servlet java code so that i can use these. Right now, I am trying to get the form data with request.getParameter("name"); but it is return null values. I am able to get the field values using item.getFieldName() and item.getFieldValue() but these are not really usable in additional processes in the item.iterator but these are not usable in further operations. For example, I want to pull in the email address field value so that I can send an email at the end of my upload servlet. I cannot use this data if I cannot make it into a string or variable which is where I am having issues. Any advice?
jsp file:
jsp form:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Username: <input type="text" name="username" value="username"/><br>
E-mail: <input type="email" name="email" autocomplete="on"><br>
<br>
Select file to upload:<input type="file" name="uploadFile" /><br>
<input type="submit" value="Upload" />
</form>
Java file:
UploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("username");
System.out.println(id); //returns null value
String password = request.getParameter("email");
System.out.println(password);//returns null value
For using file upload you get value only in form field.
request method not work in file upload
if (ServletFileUpload.isMultipartContent(request)) {
List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multipart) {
if (!item.isFormField();
{
//Your upload file code.
}
if (item.isFormField()) {
if (item.getFieldName().equals("username")) {
String id = item.getString();
}else if (item.getFieldName().equals("email")) {
String password = item.getString();
}
}
Related
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
I have a JSP containing a form
<form action="upload" method="post" enctype="multipart/form-data">
<fieldset>
<input name="nom" class="input-xlarge focused" id="nom" type="text" value="">
<input name="date" class="input-xlarge focused" id="date" type="text" value="">
<input type="file" name="file" />
<button type="submit" class="btn btn-primary">Envoi</button>
</fieldset>
</form>
which contains 2 fields (nom and date) and also asking for a file to be uploaded on the server.
on the servlet side, I have the following:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("/")+"imgs/";
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
String nom = request.getParameter("nom");
String date = request.getParameter("date");
log.debug("upload parameters: "+nom+" "+date);
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
log.debug("File updated successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
log.debug("File upload failed: "+ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
log.debug("file upload only !");
}
//request.getRequestDispatcher("/result.jsp").forward(request, response);
}
file upload is working properly but I'm not able to retrieve my two parameters (nom and date) by using request.getParameter.
Can I retrieve parameters in a multipart/form-data ? how can I do that ?
While using enctype="multipart/form-data" you can not directly get parameters by using request.getParameter("nom");.
In this case the form fields aren't available as parameter of the request, they are included in the stream, so you need to get them from stream.
A possible way is to use commons-fileupload. Here is sample code from official documentation ( Refer to 'Processing the uploaded items' section)
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
For a regular form field
// Process a regular form field if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
... }
public class Relay extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
RequestDispatcher rd =request.getRequestDispatcher(command);
rd.forward(request, response);
System.out.println("Request forwarded to " + command + " servlet");
}
}
This is my Relay servlet, I'm sending data from this form
<form action="Relay" method="POST" enctype="multipart/form-data"> /
<input type="hidden" name="command" value="AddProduct" />
<input type="text" name="pname" value="" />
<input name="" type="submit" value="Add Product">
</form>
It is throwing a java.lang.NullPointerException.
But works fine when I remove this:
enctype="multipart/form-data"
Why do you need to add it then? Just keep it out.
If you need it in order to upload a file by <input type="file"> which you intend to add later on, then you should put #MultipartConfig annotation on your servlet, so that request.getParameter() will work and that all uploaded files can be retrieved by request.getPart().
#WebServlet("/Relay")
#MultipartConfig
public class Relay extends HttpServlet {
// ...
}
See also:
How to upload files to server using JSP/Servlet?
Parameters encoded with multipart/form-data are sent in POST body - not as regular request parameters, therefore can't be read using request.getParamter(...).
Check out Commons file upload package for multipart requests processing.
I am including this just for additional information for troubleshooting.
if you are stuck and want to know about what all parameters are coming through multipart request you can print all parameters using following code.
MultipartRequest multi = <Your code to retrieve multipart request goes here. Sorry but can not post code as I use proprietary APIs>
Enumeration en1 = multi.getParameterNames();
while (en1.hasMoreElements()) {
String strParamName = (String)en1.nextElement();
String[] strParamValues = multi.getParameterValues(strParamName);
for (int i = 0; i < strParamValues.length; i++) {
System.out.println(strParamName + "=" + strParamValues[i]);
}
}
remove the form tag and use
echo <?php form_open_multipart('Controller/function');
I got the same issue whenever I use enctype="multipart/form-data"
I didn't get the file name and when I remove that it was working fine
try it it worked for me
I want to pass two values to a servlet from a jsp page. 1- a result set value, 2- a get parameter value.
It should look something like this in jsp page:
SCcalculator.getValue(rs.getString("value1"),request.getParameter("value1"));
on the servlet side how can i receive and manipulate this data in the SCcalculator package? any suggestions please?
In your servlet class use :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String s = request.getParameter("value1");
String s1 = request.getParameter("value");
}
in JSP don't do like that, instead do :
<form action="name" method="post"> //here action=name is name of your servlet class name
<input type="text" name="value">
<input type="text" name="value1">
<input type="submit" value="Send">
</form>
Conside this example
<html>
<head>
<title>Demo application</title></head>
<body>
<form id = "form1" method = "GET" action = "../Sample Application">
link1 : <input type = "text" id = "nRequests" name = "nRequests" />
<input type = "submit" name = "submit" id = "submit"/>
</form></body></html>
Now how you servlet will accept the request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
nRequests = request.getParameter("nRequests");
In this way you can get the value from a HTML page to your servlets.
I am using a JSP page to add information through tomcat to a MySQL database which is working. I would like to add a user profile picture upload function to the form. Can I save this image to the same database entry? How will do I go about adding a browse function to the form to select the image and persist it with the rest of the data?
Form from My Jsp:
<h2>Signup Details</h2>
<form name="actionForm" action="RegistrationServlet" method ="post">
<br/>Name:<input type="text" name="name">
<br/>Address:<input type="text" name="address1">
<br/><input type="text" name="address2">
<br/>County:<input type="text" name="county">
<br/>Telephone:<input type="text" name="phone">
<br/>Email:<input type="text" name="email">
<br/>Password:<input type="password" name="password">
<br/><input type="submit" value="Submit">
Registration Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
System.out.println("In the registration Servlet");
User user = new User();
user.setName(request.getParameter("name"));
user.setPassword(request.getParameter("password"));
user.setEmail(request.getParameter("email"));
user.setTelephone(request.getParameter("phone"));
user.setCounty(request.getParameter("county"));
user.setAddress1(request.getParameter("address1"));
user.setAddress2(request.getParameter("address2"));
RegisterUser.addUser(user);
response.sendRedirect("Welcome.jsp");
} catch (Throwable exc)
{
System.out.println(exc);
}
public class Relay extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
RequestDispatcher rd =request.getRequestDispatcher(command);
rd.forward(request, response);
System.out.println("Request forwarded to " + command + " servlet");
}
}
This is my Relay servlet, I'm sending data from this form
<form action="Relay" method="POST" enctype="multipart/form-data"> /
<input type="hidden" name="command" value="AddProduct" />
<input type="text" name="pname" value="" />
<input name="" type="submit" value="Add Product">
</form>
It is throwing a java.lang.NullPointerException.
But works fine when I remove this:
enctype="multipart/form-data"
Why do you need to add it then? Just keep it out.
If you need it in order to upload a file by <input type="file"> which you intend to add later on, then you should put #MultipartConfig annotation on your servlet, so that request.getParameter() will work and that all uploaded files can be retrieved by request.getPart().
#WebServlet("/Relay")
#MultipartConfig
public class Relay extends HttpServlet {
// ...
}
See also:
How to upload files to server using JSP/Servlet?
Parameters encoded with multipart/form-data are sent in POST body - not as regular request parameters, therefore can't be read using request.getParamter(...).
Check out Commons file upload package for multipart requests processing.
I am including this just for additional information for troubleshooting.
if you are stuck and want to know about what all parameters are coming through multipart request you can print all parameters using following code.
MultipartRequest multi = <Your code to retrieve multipart request goes here. Sorry but can not post code as I use proprietary APIs>
Enumeration en1 = multi.getParameterNames();
while (en1.hasMoreElements()) {
String strParamName = (String)en1.nextElement();
String[] strParamValues = multi.getParameterValues(strParamName);
for (int i = 0; i < strParamValues.length; i++) {
System.out.println(strParamName + "=" + strParamValues[i]);
}
}
remove the form tag and use
echo <?php form_open_multipart('Controller/function');
I got the same issue whenever I use enctype="multipart/form-data"
I didn't get the file name and when I remove that it was working fine
try it it worked for me