OOP-ResearchMake It Simpler by Object Oriented Programming

File Upload Servlet/JSP Example by multipart/form-data : How to create Photo Album

Example for File Upload Servlets by multipart/form-data. Free Source code of Photo Album by JSP/Servlet. Accept only JPG/GIF. Limit the file size to be uploaded. Login by the user name and password.
This is the free source code example of Photo Album by JSP/Servlet with multipart/form-data. By the user name and password, only the registered users can longin to this system. And the unique directory will be allocated per user. The uploaded files will be saved there. The file upload Servlet accepts only the JPEG and GIF files. In addition, if the size of the file to be uploaded exceeds 30 KB, the file upload Servlet will throw the Exception. The users can view the list of the uploaded files.

Another solution... file upload by e-mail :

The file upload by multipart/form-data works in most cases. However, a growing number of the WAP phones are shipped with the digital cameras, i.e. the users can take the pictures by their mobile phones and send them to their friends by the e-mails. And, by OOP Pop3Receiver API, you can take the advantage of this feature. It is the Java API for connecting to the POP3 servers through JavaMail API, and you can extract the file attachment from the received e-mail. Be ready for file upload from WAP phone!

Download the source code of this example:

Related Pages:


About this source code example...

The main subjects of this example are:

  • Simple access privilege by the user name and password in the text file. To track the login information, HttpSession object will be used.
  • How to save the uploaded files into the unique directory per user. To make it possible, the destination Servlet/JSP allocates the unique directory for each user. This example saves the uploaded file by the file name same as the original file name on the client side. If you'd like to save the uploaded file in the file name allocated by the server side (to avoid the existing file being overridden), please try another example.
  • How to set the maximum file size to be uploaded
  • How to restrict the mime-type (Content-Type) of the file to be uploaded. For example, if you'd like to allow the users to upload the files only of image/gif, image/jpeg or image/pjpeg, how can you do it?
OOP MimeParser is the Java API for File upload Servlet/JSP. With the easy programming interface of this API, a few lines of code will be enough for your file upload Servlet/JSP. This API parses the multipart/form-data for the file upload request from the CGI FORM. You can specify the maximum size of the file to be uploaded. If the larger file is uploaded, this API throws the exception. In this case, your Servlet/JSP can catch the exception and show the appropriate message.
Moreover, you can restrict the mime-type (Content-Type) of the file to be uploaded. If the user tries to upload the file of other mime-type (Content-Type), this API throws the exception and your Servlet/JSP has a chance to catch the exception.
In this Java API, you can write:
  • The maximum file size to be uploaded
  • The list of the acceptable mime-types (Content-Types)
in the property files. So, you can change the maximum file size, and can add/delete the acceptable mime-types (Content-Types) without updating the source code of your JSP/Servlet! For details of the property files for this Java API, please visit the link below: By the help of this Java API, only the tricks of this example are:
  • Access privilege by the user name and password.
  • How to allocate the unique directory for each user.
To make the things easier, the valid pairs of the user name and password are written in the text file. But, this is not good solution for the production environment. In your production environment, please take the greater care on the security. Anyway, the pair of the user name and password sent from the CGI FORM will be compared against the ones listed in the text file. By this way, only the user with the valid user name and password can login to this example. Once the user login to this example, the user name can be tracked by the HttpSession object within Cookie across the subsequent requests. It looks like this:

    public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException,IOException{
	String user=req.getParameter("user");
	String pass=req.getParameter("pass");
	if(user==null || pass==null){
	    (req.getRequestDispatcher(BAD_USER)).forward(req,res);
	    return;
	}
	user=user.trim();
	pass=pass.trim();
	if(user.equals("") || pass.equals("")){
	    (req.getRequestDispatcher(BAD_USER)).forward(req,res);
	    return;
	}
	// For each request, the user-password map
	// is re-loaded.
	// So, the changes to the user-password map
	// can be reflected without re-starting the server.
	ClassLoader cl=Thread.currentThread().getContextClassLoader();
	InputStream is=cl.getResourceAsStream(PASS_FILE);
	Properties prop=new Properties();
	prop.load(is);
	is.close();
	if(!(prop.containsKey(user))){
	    (req.getRequestDispatcher(BAD_USER)).forward(req,res);
	    return;
	}
	if(!((prop.getProperty(user)).equals(pass))){
	    (req.getRequestDispatcher(BAD_USER)).forward(req,res);
	    return;
	}

	LoginDir login=new LoginDir(root,user);
	HttpSession session=req.getSession(true);
	session.setAttribute("login",login);
	(req.getRequestDispatcher(LIST_FILE)).forward(req,res);
	return;
    }


When the user uploads the files by the CGI FORM for the multipart/form-data request, the destination Servlet picks up the user name from HttpSession object by Cookie. The source code fragment of the destination Servlet looks like this:

    private static MimeParser mime=null;
    private static Set accept_type=null;

    public void init()
	throws ServletException{
	try{
	    mime=MimeParser.getInstance();
	    // Read the accepatble mime-types from
	    // WEB-INF/classes/AcceptMime.properties
	    accept_type=AcceptMime.getAcceptMime();
	}
	catch(Exception ex){
	    ex.printStackTrace();
	    throw (new ServletException(ex));
	}
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException,IOException{
	HttpSession session=req.getSession(true);
	if(session.isNew()){
	    (req.getRequestDispatcher(NO_SESSION)).forward(req,res);
	    return;
	}
	Object obj=session.getAttribute("login");
	if(obj==null){
	    (req.getRequestDispatcher(INVALID)).forward(req,res);
	    return;
	}
	LoginDir login=(LoginDir)obj;
	// The uploaded files will be saved into the
	// sub-directory under the root directory.
	// And this sub-directory is allocated for each user.
	String user=login.getUser();
	try{
	    // The maximum file size is specified by
	    // WEB-INF/classes/MimeParser.properties ...
	    mime.parseAndSave(req,user,accept_type);
	}
	// If the Content-Length of the request exceeds
	// the specified value...
	catch(TooLargeBodyException ex){
	    String exception=ex.getMessage();
	    req.setAttribute("exception",exception);
	}
	// If the file size exceeds the specified value...
	catch(TooLargeFileException ex){
	    String exception=ex.getMessage();
	    req.setAttribute("exception",exception);
	}
	// If the mime-type is not listed in
	// WEB-INF/classes/AcceptMime.properties ...
	catch(InvalidContentTypeException ex){
	    String exception=ex.getMessage();
	    req.setAttribute("exception",exception);
	}
	catch(Exception ex){
	    throw (new ServletException(ex));
	}
	(req.getRequestDispatcher(LIST_FILE)).forward(req,res);
	return;
    }


When the user uploads the file, the web browser detects the file name on the client side and sends it to the server as a part of the multipart/form-data request. The destination Servlet in this example saves the uploaded file by this file name. For instance, if the user name is foo and the user uploads bar.gif, then the uploaded file will be saved as:
  • (save_root)/foo/bar.gif
Please note that the save_root must be specified by:
  • WEB-INF/classes/MimeParser.properties
To track the user name across the HTTP requests, this example fully depends on the HttpSession object by Cookie. So, this example will also be a good example for how to use HttpSession in Servlet/JSP programming.

Thus, a few lines of source codes are enough for the file upload Servlet by multipart/form-data.
Please note that the above Servlet has the static reference to the MimeParser object. Because all the methods of MimeParser are Thread Safe, the single instance can be shared among the concurrent requets. For details about the Thread Safety of MimeParser, please read:
Go Site Map

More source code examples...

On our web site, there are more source code examples for how to upload the files by JSP/Servlet through multipart/form-data request. Please also try and download these examples too:
[The simplest example for file upload JSP by multipart/form-data]

This example consists of only one JSP and its helper classes. It is the simplest example in the world for how to upload files by JSP through multipart/form-data! If this is your first time to try OOP MimeParser, please try it and download its source code.
[The very simple example for file upload JSP by multipart/form-data]

This example consists of only one JSP and its helper classes. It is the very simple example for how to upload files by JSP through multipart/form-data. But, to avoid the existing file being overridden, the unique file name can be allocated to each uploaded file.
[How to specify the file name by the CGI FORM]

You can specify the file name by the HIDDEN INPUT in the departing CGI FORM.
If the HIDDEN INPUT whose name is same as the FILE INPUT is included in the CGI FORM, MimeParser is wise enough to detect it. And the value of such a HIDDEN INPUT will be used as the file name on the server side. For example:
CGI FORM for file upload with file name by JSP
Note that both INPUT in this CGI FORM has the same name. In the above example, the uploaded file is always saved as userphoto.gif on the local file system, regardless of the file name of the client side. Only the first HIDDEN INPUT before the FILE INPUT can be picked up as the file name by MimeParser.

If you have an interest in this strategy, please try this example. In this example, the unique directory can be allocated per each user. And, within the allocated directory, the unique file name can be determined by the departing JSP. The unique file name will be merged into the value of the HIDDEN INPUT in the CGI FORM.
To track the directory for each user, the above example fully depends on the HttpSession by Cookie. So, it will be a good example for how to use HttpSession in Servlet/JSP programming.
[How to save the uploaded file by the original file name]

The web browser detects the file name on the client side and sends it the server, so the original file name on the client side can be used for the file name on the server side. If you'd like to save the uploaded file in the file name same as the one on the client side, please try this example and download its source codes. In this example, the unique directory can be allocated per each user. To track the directory for each user, this example fully depends on the HttpSession by Cookie. So, it will be a good example for how to use HttpSession in Servlet/JSP programming.
[Get the binary contents of the uploaded file]

You may not want to save the uploaded file on the file system. Rather, you'd like to get its binary contents directly. Don't worry. OOP MimeParser also implements the methods for this case. To show you how to get the binary contents of the uploaded file, we build this example. By the destination Servlet, the binary contents of the upload the file will be attached to the e-mail along with the file name and the Content-Type. Then, the e-mail will be sent at the scheduled time by JavaMail API. Please try it and download its source code.

Go Site Map

Try this example and download the required APIs...

The source code of this example is available at the link below:

Along with this source code example, please also download OOP MimeParser, which is available at Java API Shop by OOP-Research. There, you can select the 30 days FREE trial version.
Go Site Map

Installation...

First of all, please read through README.html in the distribution of OOP MimeParser and edit the property resource file. If you use the trial version, please set your serial ID in the property resource file.
OOP MimeParser requires the following APIs:

After the source code of this example extracted, please place all the required JAR files and property file. As a result, the mime_login directory will include the following JAR files and property file:
  • mime_login/WEB-INF/lib/mime.jar
  • mime_login/WEB-INF/lib/oop_util_1_x.jar
  • mime_login/WEB-INF/lib/activation.jar
  • mime_login/WEB-INF/lib/mail.jar
  • mime_login/WEB-INF/classes/MimeParser.properties
  • mime_login/WEB-INF/classes/AcceptMime.properties
Note that mime.jar and oop_util_1_x.jar are included in OOP MimeParser. Be sure to give the Read permission for these files.

Then, please edit:
  • mime_login/WEB-INF/classes/MimeParser.properties
so that it points the directory where you'd like to save the uploaded files. Open this property file by your favorite text editor and modify the value of:
  • file_root=/export/home/foo/mywebapps/WEB-INF/mime_file
In case of Windows OS, the intended directory can be specified by something like:
  • C:\\temp\\mywebapps\\mime_file
Please note that all the back-slash must be escaped in Windows OS.

In addition, please give the Write permission to the specified directory. For example, if the Servlet/JSP server (such as Apache Tomcat) is running as the user of nobody, please give Write permission for nobody to the specified directory.

NOTE for oop_util_1_x.jar:
If you have the older version oop_util_1_x.jar, please replace it with the new one. In other words, please be sure to find only the latest version of oop_util_1_x.jar under WEB-INF/lib directory.

NOTE for JBuilder:
Please add all the jar files above to Required Libraries of your project.

Go Site Map

Caution!
All the APIs for Servlet/JSP introduced by this web site are now included in Bento framework:
  • Simpler than JSTL or Apache Struts
  • MVC framework by HTML
  • Input validation from CGI FORM
  • Easy user authentication
  • Easy localization (L10n)
To download the APIs and source code examples, please visit the web site of Bento framework.


JBuilder 2007


General Information

For Java Development

Java and all Java-based trademarks and logos are trademarks or registered of Sun Microsystems, Inc. in the United States and other countries.


ALL CONTENTS COPYRIGHT 1997-2007, OOP-Research Corporation. All rights reserved.