Srikanth Technologies

Uploading File Using Servlets 3.0

At last Servlets 3.0 provides support for file uploading. We no longer need to use any other third part library (Apache's common file-upload) to deal with file uploading in Java. Servlets 3.0 API provides support for file uploading with new API related to Part. Method getPart() of HttpServletRequest provides access to multipart data sent from html form.

To use Servlets 3.0, first you have to use a web server that supports Java EE 6.0. Glassfish V3 is the first (I think) server to support Java EE 6.0 specs. The best way to get started is to download NetBeans IDE 6.8 beta, which comes with Glassfish V3, which is good enough to experiment with Java EE 6.0.

First create a new Java Web application with NetBeans 6.8 and select GlassFish v3 as the server and Java EE 6 as Java EE version. In my case I named the application as javaee6demo. You can use any name but make sure you use the same name in the URL used to invoke the pages.

The following .jsp and Servlet show how to save a file uploaded from client on the server with the filename given by the user.

upload.jsp



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Upload File</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>Select File : </td>
                <td><input  name="file" type="file"/> </td>
            </tr>
            <tr>
                <td>Enter Filename : </td>
                <td><input type="text" name="photoname" size="20"/> </td>
            </tr>
        </table>
        <p/>
        <input type="submit" value="Upload File"/>
    </form>
 </body>
</html>


UploadServlet.java

This servlet needs no entries in web.xml as it uses annotations to declare itself as servelt with a url pattern. One of the new features of Servlets 3.0 is to use annotations to declare Servlets, Filters and Listeners with annotations with no entries in web.xml (and infact no web.xml at all).

package servlets;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name="UploadServlet", urlPatterns={"/upload"})     // specify urlPattern for servlet
@MultipartConfig                                               // specifies servlet takes multipart/form-data
public class UploadServlet extends HttpServlet {
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            // get access to file that is uploaded from client
            Part p1 = request.getPart("file");
            InputStream is = p1.getInputStream();

            // read filename which is sent as a part
            Part p2  = request.getPart("photoname");
            Scanner s = new Scanner(p2.getInputStream());
            String filename = s.nextLine();    // read filename from stream

            // get filename to use on the server
            String outputfile = this.getServletContext().getRealPath(filename);  // get path on the server
            FileOutputStream os = new FileOutputStream (outputfile);
            
            // write bytes taken from uploaded file to target file
            int ch = is.read();
            while (ch != -1) {
                 os.write(ch);
                 ch = is.read();
            }
            os.close();
            out.println("<h3>File uploaded successfully!</h3>");
        }
        catch(Exception ex) {
           out.println("Exception -->" + ex.getMessage());
        }
        finally { 
            out.close();
        }
    } // end of doPost()
 } // end of UploadServlet

Deploy the application and run the following Url assuming Glassfish V3 is running on port no. 8080 (default port number)
http://localhost:8080/javaee6demo/upload.jsp
Select a file using Choose File button, which is displayed for File control. Enter a filename that you want to use to save the file on the server. Click on Upload File button to invoke servlet that saves the content of the file on the server. In this application the location where file is saved is "C:\javaee6.0\javaee6demo\build\web" as the project was created in "c:\javaee6.0" folder.