View RSS Feed

My Java Tips

Sending files from Servlet

Rate this Entry
by , 11-15-2011 at 06:35 PM (855 Views)
In this post, I will present an example which will show how to move the selected file (drop down menu) form a servlet to another servlet which performs operations on the file.


I have created 3 Javafiles namely:

- HelloServlet(Servlet)
- GetImg (Servlet)
- ImgCompare (simpleJava class)

HelloServlet contains a HTML form that has a dropdown menu. Menu contains 2 JPG files. You should have following images at the given path:

C:\image1.jpg
C:\image2.jpg

Or simple you can edit the HelloServlet, and give your own files with the path.

Java Code:
public class HelloServlet extends HttpServlet {
  public void service (HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
  {
        PrintWriter out = res.getWriter();
        out.println("Welcome");
        out.println("
enctype=\"multipart/form-data\">");

out.println("

");
out.println("



");
out.println("


");
        out.close();
  }
}

GetImg is a servlet that is called by HelloServlet. It gets the image path, reads the image file, and then creates an object of ImgCompare. ImgCompare has a constructor which takes file object as argument.


public class GetImg extends HttpServlet {
  public void doGet (HttpServletRequest req,
                                         HttpServletResponse res)
        throws ServletException, IOException
  {
        PrintWriter out = res.getWriter();
        String selectedImg = req.getParameter("imagedd");
        out.println("Hello all!");
        File file = new File (selectedImg);

       ImgCompare obj = new ImgCompare(file);
       obj.startComparision();

        out.close();
  }
}

In ImgCompare class, startComparision() will contains code to compare the files. This will be your class. I have made this just to show you how to do that.


public class ImgCompare  {

	private File file;

  public ImgCompare(File file)
  {
	  this.file = file;
  }

  public void startComparision()
  {
	  System.out.println("File received from Servlet has size: " + file.length());
	  System.out.println("File comparision started.");
  }
}
Happy coding.

Submit "Sending files from Servlet" to Facebook Submit "Sending files from Servlet" to Digg Submit "Sending files from Servlet" to del.icio.us Submit "Sending files from Servlet" to StumbleUpon Submit "Sending files from Servlet" to Google

Categories
Java EE

Comments