File uploading is a very common task in web applications and it is frequently necessary to upload a file from client to server. In HTML forms the input type “file” allows the visitor browse the local file system to select the file. When the file is selected it is sent to server as a part of a POST request. During this there are two mandatory restrictions applied to the form with input type file: it must contains attribute enctype set to value multipart/form-data and its method should be POST. Thus, entire request in sent to server in encoded form. JSP container does not parse the content of requests with type multipart. That is why JSP or servlet processing incoming file data has to use own means to handle request and extract a file from there.

We will use Apache commons FileUpload to handle the file on server.
Once it is downloaded, we should copy the jar files under WEB-INF/lib of our application. If we put a library into lib directory newly, we should be aware of the fact that we need to restart Tomcat.
We will have two files: test.jsp (contains the form for file upload) and the second is process.jsp (handles the form data)

test.jsp

1
2
3
4
5
6
7
8
9
10
<html>
   <head>
   </head>
   <body>
      <form action="process.jsp" method="post" enctype="multipart/form-data">
          <input type="file" name="image" id="image" size="21"/>
          <input type="submit" value="Send"/>
      </form>
   </body>
</html>

process.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<%@page import="org.apache.commons.fileupload.*"%>
<%@page import="org.apache.commons.fileupload.disk.*"%>
<%@page import="org.apache.commons.fileupload.servlet.*"%>
<%@page import="javax.imageio.ImageReader"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="javax.imageio.stream.ImageInputStream"%>

<%
    final int MAX_ALLOWED_SIZE = 100000; // 150 KB
    final int MAX_ALLOWED_WIDTH = 100;
    final int MAX_ALLOWED_HEIGHT = 100;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    java.util.List /* FileItem */ items = upload.parseRequest(request);

    // Process the uploaded items
    java.util.Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            //processFormField(item);
        } else {
             String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();

                java.io.File fullFile  = new java.io.File(item.getName());  
                java.io.File savedFile = new java.io.File(getServletContext().getRealPath("/uploads"),
                fullFile.getName());
                item.write(savedFile);
               
                int width = 0;
                int height = 0;

                ImageInputStream in = ImageIO.createImageInputStream(savedFile);
                try {
                        final java.util.Iterator readers = ImageIO.getImageReaders(in);
                        if (readers.hasNext()) {
                                ImageReader reader = (ImageReader) readers.next();
                                try {
                                        reader.setInput(in);
                                        width =  reader.getWidth(0);
                                        height = reader.getHeight(0);
                                } finally {
                                        reader.dispose();
                                }
                        }
                } finally {
                        if (in != null) in.close();
                }
               
               
                if(sizeInBytes > MAX_ALLOWED_SIZE){
                    out.print("Maximum file size exceeded!" );
                    savedFile.delete();
               
                }else if(width > MAX_ALLOWED_WIDTH || height > MAX_ALLOWED_HEIGHT){
                    out.print("Maximum image size exceeded!" );
                    savedFile.delete();
                }else{
                    out.print("-- filename: " + fileName);
                    out.print("-- contentType: " + contentType);
                    out.print("-- sizeInBytes: " + sizeInBytes);
                    out.print("-- width: " + width);
                    out.print("-- height: " + height);
                }
        }
    }
   
%>

When you select a file and submit the form, if you get java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream most probably commons-io-1.4 library is missing.

Download it from Apache Commons IO and put to your lib directory.

Thanks to ServletFileUpload class, we can get file name, content type, size attributes of upload file.

In our example we upload the files into /uploads directory in our context. If this directory is missing you will get java.io.FileNotFoundException:, so be sure that you have created this directory.

We are getting the width and height of our image, using the ImageIO and ImageReader classes.

The code is self explanatory enough and how the validation occurs is obvious.

Development, JSP & Servlets - Posted by admin on April 18, 2010

No Comments

Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

Leave a Reply