Download Java Servlet / Jsp along with form values

I have a jsp form that accepts information about an employee’s name, gender, age, email address and

0
source share
1 answer

Servlet 3.0 container has standard support for multi-part data. First you must write an HTML page in which the file is entered along with other input parameters.

<form action="uploadservlet" method="post" enctype="multipart/form-data">
    <input type="text" name="name" />
    <input type="text" name="age" />
    <input type="file" name="photo" />
    <input type="submit" />
</form>

Now write a UploadServlet that uses the Servlet 3.0 download API. Here is the code that demonstrates the use of the API. A fist that handles multiplayer servlet data must define MultiPartConfig using either of two approaches:

  • @MultiPartConfig servlet class annotation
  • web.xml, <multipart-config> <servlet>.

UploadServlet,

@MultipartConfig
 public class UploadServlet extends HttpServlet
 {
   protected void service(HttpServletRequest request, 
       HttpServletResponse responst) throws ServletException, IOException
   {
      Collection<Part> parts = request.getParts();
      if (parts.size() != 3) {
         //can write error page saying all details are not entered
       }

       Part filePart = httpServletRequest.getPart("photo");
       InputStream imageInputStream = filePart.getInputStream();
       //read imageInputStream
       filePart.write("somefiepath");
       //can also write the photo to local storage

       //Read Name, String Type 
       Part namePart = request.getPart("name");
       if(namePart.getSize() > 20){
           //write name cannot exceed 20 chars
       }
       //use nameInputStream if required        
       InputStream nameInputStream = namePart.getInputStream();
       //name , String type can also obtained using Request parameter 
       String nameParameter = request.getParameter("name");

       //Similialrly can read age properties
       Part agePart = request.getPart("age");
       int ageParameter = Integer.parseInt(request.getParameter("age"));



    }

}

Sevlet 3.0 Container, Apache Commons. Apache Commons:

:

+2

All Articles