File Upload in Servlet 3.0

Nikolaus Gradwohl2010-09-01T19:35:00+00:00

I played around a bit with the new servlet-api 3.0 and tomcat7 and i really like it. it has some nice features like servlet declaration using annotations or the support for asynchornous requesthandling, but the feature that i really really love is the support for file upload.

To handle a file upload form like this

<html>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
<input type="file" name="filename"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

is to mark the servlet with an annotation and access the uploaded file using 'request.getPart("filename")' like this

package at.hpc.servlettest;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet(name="testUpload", urlPatterns={"/upload"})
@MultipartConfig
public class TestUpload extends HttpServlet {
    protected void doPost( HttpServletRequest req, HttpServletResponse res ) 
               throws ServletException, IOException {
        Part part = req.getPart("filename");

        res.setContentType( part.getContentType());
        res.setHeader( "disposition", "inline" );

        OutputStream out = res.getOutputStream();
        InputStream in = part.getInputStream();

        byte buffer[] = new byte[ 4048 ];
        int n = 0;
        while ((n = in.read( buffer )) > 0) {
            out.write( buffer, 0, n );
        }
        out.close();
    }
}

This is a really silly example that just copies the uploaded file back to the browser, but it shows how clean and simple handling fileuploads gets with this api - this is the feature i have been waiting for years!

read more ...