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



Home    Blogs

Post Your Comment

Image

Enter the code given in the above image :
Your Name :
Your Email Address :
Comment :

Comments


Posted By arvind On 25-Dec-09 10:36:59 PM

Sir i have used your this example in netbeans 6.8. I build and deploy it succefully. Also it is running but when i try to upload any file even the simple text file it is throwing the excption giving "Exception--> no line found"
kindly help me.



Posted By sobha On 29-Jan-10 04:26:30 PM

thanku sir,
2dy i learnt a new application..



Posted By rasool On 16-Feb-10 06:38:50 PM

pretty cooool Thank you



Posted By jhuesos On 16-Apr-10 02:44:29 PM

Thanks a lot!! It helped me A LOT. Thanks



Posted By hoho On 19-May-10 04:57:31 AM

how can i define where the file will be save instead of ....\build\web\



Posted By tarang On 10-Jul-10 12:07:25 PM

really appreciate but you should give also screenshot for how to deploy



Posted By Venkat On 09-Aug-10 09:01:00 PM

I've tried this example with Eclipse, no problem in execution. But I can't find the file which I've uploaded... I've searched inside the project directory, but I can't find it. Do anyone know why does it happened so??? Help me..



Posted By Adam Musial-Bright On 05-Sep-10 04:43:19 PM

Nice example - worked for me too - thanks!



Posted By iscvhfc1334 On 04-Dec-10 12:37:36 AM

Excelente mil gracias pero como le hago para que ahora pueda descargar los archivos que están en el servidor una vez que ya se subieron gracias muy buen articulo….



Posted By Mittal On 05-Feb-11 08:04:57 PM

thanks,now can you tell me filters in Servlet 3.0



Posted By Ram On 04-Mar-11 02:08:44 AM

This Example run fine in GlashFish, but i need to run it with Tomcat is it possible? Congratulations your blog is Great!!! :D



Posted By sn On 23-Mar-11 11:34:04 AM

Nice tutorial,
here is another tutorial http://www.servletworld.com/servlet-tutorials/servlet3/multipartconfig-file-upload-example.html that explains @MultipartConfig in greater depth.



Posted By Johan Mynhardt On 15-Apr-11 08:12:55 PM

To change the default location, use a file descriptor, and use that in the FileOutputStream constructor; ie.:

File file = new File("/tmp/test");
FileOutputStream fos = new FileOutputStream(file);

Note that the actual file will be "test".



Posted By bhavani On 28-Jun-11 09:02:24 PM

sir, can u please post how to download a file which was stored at server's database.



Posted By bhavani On 28-Jun-11 09:11:48 PM

sir, can u suggest how to download file of any type stored at server



Posted By prakash On 18-Jan-12 05:48:29 PM

I am using above code in Netbeans 7.0.1 with Apache-Tomcat server but getting a NullPointerException while doing request.getPart("file").

Please help me.



Posted By Amit On 20-Aug-12 12:54:44 PM

For the Following Line,,, I am really very much Thankful to THE WRITER... :)

Part p1 = request.getPart("file");



Posted By Diksha On 27-Mar-14 12:17:14 PM

Sir
I am using eclipse juno and facing problem while running ur program on glassfish server 7,can u plz tell me how to provide path for file to be stored.
It will be great help .
Kindly Help

Copyright © Srikanth Technologies. All rights reserved.