8

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
}
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • possible duplicate of [How to upload files to server using JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet) – Buhake Sindi Jan 21 '13 at 08:51
  • BalusC wrote an excellent answer for a [related SO question](http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet) concerning File Upload using Serlvet 3.0. – Buhake Sindi Jan 21 '13 at 08:46

1 Answers1

14

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 {

}
SANN3
  • 9,459
  • 6
  • 61
  • 97