OOP-ResearchMake It Simpler by Object Oriented Programming

Source code example of File Upload JSP/Servlet by multipart/form-data : Simplest example JSP for multipart/form-data

Source code example of File Upload JSP/Servlet by multipart/form-data. In this source code example, JSP/Servlet can restrict the maximum file size and the mime-types (Content-Types) to be uploaded. Moreover, JSP/Servlet can set the maximum width/height of the image file (JPEG, GIF or PNG).
If the user tries to upload the larger files or the file of invalid mime-types (Content-Types), the JSP refuses the request. The maximum file size, the maximum width/height of the image file, and the list of the acceptable mime-types (Content-Types) can be written in the property files.
After InputStream of multipart/form-data parsed, the binary contents of the uploaded files can be saved on the server side. Just a single JSP can be responsible for all these tasks! This is the simplest example of file upload JSP/Servlet in the world. Please download the source code and try it.

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...

This source code example consists of only one JSP and its helper classes. It is the simplest example in the world for how to upload the files by Servlet/JSP through multipart/form-data!

The main subjects of this example are:

  • How to set the maximum size of the file 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?
  • How to set the maximum width/height of the image files (JPEG, GIF or PNG)
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. You can also limit the width/height of the image file (JPEG, GIF or PNG) 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 maximum width/height of the image file
  • The list of the acceptable mime-types (Content-Types)
in the property files. So, you can change the maximum file size and the maximum width/height, 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, there is no trick in this example.
Let's look into the source code fragment of the destination JSP:

<%!
    private static MimeParser mime=null;
    private static Set accept_mime=null;

    public void jspInit(){
        try{
            mime=MimeParser.getInstance();
            <%-- This method reads the list of --%>
            <%-- the accepatble mime-types from --%>
            <%-- WEB-INF/classes/AcceptMime.properties --%>
	    accept_mime=AcceptMime.getAcceptMime();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
%>

<%
    <%-- This method saves the uploaded file. --%>
    mime.parseAndSave(request,"upfiles",accept_mime);
%>


Thus, a few lines of source codes are enough for the file upload JSP by multipart/form-data.
Please note that the above JSP 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

Width/height of the image file (JPEG, PNG or GIF) to be uploaded...

If your web application accepts the multipart/form-data request for the image file (JPEG, PNG or GIF), you may want to set the maximum width/height of the image file to be uploaded. (As for the maximum file size, please read another page.) For example, you may build Servlet/JSP for the online photo album, and you may want to set the maximum width/height of the JPEG to be uploaded.

With this Java API, your Servlet/JSP can easily set the maximum width/height of the image file to be uploaded. All what you need is to place:

  • ImageSizeChecker.properties
into
  • (docBase)/WEB-INF/classes
of your web application context.
In addition, please edit:
  • (docBase)/WEB-INF/classes/MimeParser.properties
and specify the maximum width/height in it.

With this configuration, the following methods will check the width/height of the image file to be uploaded:
  • parseAndSave(HttpServletRequest req, String dir, Set mime)
  • parseAndSave(HttpServletRequest req, String ch, String dir, Set mime)
  • parseAndSave(HttpServletRequest req, String dir, int max, Set mime)
  • parseAndSave(HttpServletRequest req, String ch, String dir, int max, Set mime)
  • parseOnly(HttpServletRequest req, Set mime)
  • parseOnly(HttpServletRequest req, String ch, Set mime)
  • parseOnly(HttpServletRequest req, int max, Set mime)
  • parseOnly(HttpServletRequest req, String ch, int max, Set mime)
If the width or height of the uploaded image file is larger than the specified one, these methods will throw:
  • com.oopreserch.util.LargeImageException
From this exception, your Servlet/JSP can get:
  • The width of the uploaded image file
  • The height of the uploaded image file
  • The maximum width to be allowed
  • The maximum height to be allowed
  • The file name
So, you can show the helpful message to your user.

Go Site Map

Check the binary contents of the uploaded file...

Let's think about how MimeParser checks the mime-type (Content-Type) of the uploaded file. It works like this:

  • Your JSP/Servlet shows the CGI FORM with multipart/form-data, by which the user can upload the file.
  • When the user selects the file from the local file system, the web browser resolve the mime-type based on the file extension.
  • The web browser encodes the binary contents of the selected file and sends them to your JSP/Servlet, along with the resolved mime-type.
  • MimeParser (which works within your JSP/Servlet) retrieves the mime-type, which is sent from the web browser. This mime-type is compared to the mime-types listed in the property file, and MimeParser decides if the uploaded file is acceptable or not.
It will be the rare case, but the user may try to upload the file with the invalid extension. For example, the user may try to upload the text file, whose file name is:
  • myphoto.jpg
In this case, the web browser may resolve its mime-type as image/jpeg, and send this wrong mime-type to your JSP/Servlet. MimeParser on your JSP/Servlet will rely on this wrong mime-type, and accept the uploaded file. But, this is not what you want.

To avoid this situation, MimeParser can check if the binary contents of the uploaded file match with the expected pattern for the specific mime-type (Content-Type). After the mime-type (which is sent from the web browser) is found in the property file, MimeParser will inspect the binary contents of the uploaded file. If the binary contents do not match with the expected pattern for the mime-type, MimeParser will throw CorruptedBinaryContentsException.
To check the binary contents for the specific mime-type, this Java API defines the very simple interface. It is:
  • com.oopreserch.util.BinaryChecker
and has only one method.
There are so many mime-types in the world, and it is impossible to implement this interface for all the available mime-types. Rather, the implementations for only the typical mime-types are included in this Java API.
Also in the property file, you can list the fully qualified class names of the implementations. This means you can add your own implementations of BinaryChecker interface.

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 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.
[More practical example, Photo Album]

The practical example source code for the simple Photo Album is also available on our site. Because it is the Photo Album, it implements the following features:
  • Simple access privilege by the user name and password in the text file. To track the login information, HttpSession object will be used.
  • The unique directory will be allocated per user.
  • Only the JPEG and GIF files can be uploaded
  • The uploaded files will be saved as the file name same as the original file name on the client side.
The pairs of the valid user name and password are written in the text file, and the user will be asked to type the user name and password. Once s/he enters to this system, s/he can view the list of the uploaded files. 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.

You will be surprised at how the things can be easy by OOP MimeParser.

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...

If you extract this example in:

  • /home/foo/tmp
you will find:
  • /home/foo/tmp/mime_example_5
In this directory, you will find:
  • /home/foo/tmp/mime_example_5/mime_5
Please copy mime_5 into the root directory of your JSP/Servlet server. For example, if the root directory of your JSP/Servlet server is:
  • /home/foo/webapps
please copy mime_5 there. And please specify:
  • /home/foo/webapps/mime_5
as the docBase directory of the new context: In case of Apache Tomcat, your server.xml will include the lines like:


   <Context path="/mime_5" 
      docBase="/home/foo/webapps/mime_5">
   </Context>


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_5 directory will include the following JAR files and property file:
  • mime_5/WEB-INF/lib/mime30.jar
  • mime_5/WEB-INF/lib/oop_util_2_x.jar
  • mime_5/WEB-INF/lib/activation.jar
  • mime_5/WEB-INF/lib/mail.jar
  • mime_5/WEB-INF/classes/MimeParser.properties
  • mime_5/WEB-INF/classes/AcceptMime.properties
  • mime_5/WEB-INF/classes/ImageSizeChecker.properties
Note that mime30.jar and oop_util_2_x.jar are included in OOP MimeParser. Be sure to give the Read permission for these files.

You need to edit all the property files above. Among them, file_root property in:
  • mime_5/WEB-INF/classes/MimeParser.properties
is very important. The value of this property should match with docBase directory. In the above example, the value of this property will be:
  • /home/foo/webapps/mime_5
Then, all the uploaded files will be saved in:
  • /home/foo/webapps/mime_5/upfiles
In case of Windows OS, the intended directory can be specified by something like:
  • C:\\temp\\webapps\\mime_5
Please note that all the back-slash must be escaped in Windows OS.

Please don't forget to 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 this directory.

NOTE for oop_util_2_x.jar:
If you have the older version oop_util_2_x.jar, please replace it with the new one. In other words, please be sure to find only the latest version of oop_util_2_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.