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
}
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With