Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't the servlet retrieve the part ? It shows null as the file name

The html snippet sends a post request to a servlet named servlet. The request is of type multipart/form-data.But servlet finds nothing and prints null for the name of the part I try to retrieve. Why is that ?

<form method="post" action="servlet" enctype="multipart/form-data">
        <input type="file" value="browse" name="FileShared" />
        <input type="submit" value="submit" />
 </form>

import javax.servlet.http.Part;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    //String fileName = request.getPart("FileShared").getName(); 
    // Throws a nullpointer exception if I don't comment the above statement
    PrintWriter writer = response.getWriter();
    //writer.println(fileName);
    Collection<Part> c = request.getParts();
    Iterator i = c.iterator();
    while(i.hasNext()) {
        writer.println("Inside while loop"); // This statement never gets printed
        writer.println(i.next());
    }
    writer.println("outside while loop"); // Only this statement gets printed
}
like image 769
Suhail Gupta Avatar asked Jan 21 '13 08:01

Suhail Gupta


1 Answers

If you want to use Servlet 3.0 HttpServletRequest#getParts() method , then you must annotate your servlet with @MultipartConfig.

Example :

@WebServlet(urlPatterns={"/SampleServlet"})
@MultipartConfig
public class SampleServlet extends HttpServlet {

}
like image 69
SANN3 Avatar answered Oct 12 '22 12:10

SANN3