-1

I have a jsp form that accepts details about Employee name, sex, age, E-mail address and a

Tsega Eb
  • 1
  • 1
  • 1
  • 2
  • 1
    possible duplicate of [How to upload files in JSP/Servlet?](http://stackoverflow.com/a/2424824/157882) – BalusC Jun 27 '12 at 00:02

1 Answers1

2

Servlet 3.0 container's has standard support for multipart data. First you should be writing a HTML page which takes the file input 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 which uses the Servlet 3.0 Upload API. Here is the code which demonstrates the usage of API. Fist the servlet handling multipart data should define MultiPartConfig using any of the two approaches:

  • @MultiPartConfig annotation on Servlet Class
  • In web.xml, by adding <multipart-config> entry inside <servlet> definition.

Here is the 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"));



    }

}

If you are not using Sevlet 3.0 Container, you should be truing Apache Commons File Upload. Here are the links for using Apache Commons File Upload:

References:

Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50