Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading Excel file from server using servlets

I have an Excel file on the server side. How I can display it on client side browser using servlets?

Thanks in advance.

like image 481
user322012 Avatar asked May 14 '10 08:05

user322012


1 Answers

To the point: just get an InputStream of it somehow (FileInputStream is suitable) and write it to the OutputStream of the response the usual Java IO way. That's basically all. You'll only need to take care that you set the right response headers, so that the browser understands what to do with it. The Content-Type header will instruct the webbrowser what kind of file it is so that the browser knows which application to use to open it.

Here's a kickoff example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String filename = URLDecoder.decode(request.getPathInfo(), "UTF-8");
    File file = new File("/path/to/files", filename);

    response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
    response.setHeader("Content-Length", file.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        input = new BufferedInputStream(new FileInputStream(file));
        output = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[8192];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
    } finally {
        if (output != null) try { output.close(); } catch (IOException ignore) {}
        if (input != null) try { input.close(); } catch (IOException ignore) {}
    }
}

Map this servlet in web.xml on an url-pattern of /files/* so that you can get the excel file by http://example.com/contextname/files/filename.xls.

If it's actually an xlsx file, which isn't by default recognized by the average servletcontainer yet (the ServletContext#getMimeType() would then return application/octet-stream instead of the desired xlsx content type), then you need to add the following entry to the web.xml as well:

<mime-mapping>
    <extension>xlsx</extension>
    <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>

For a more advanced example of a file servlet you may find this article useful as well, it supports under each download resumes as well.

like image 180
BalusC Avatar answered Sep 20 '22 05:09

BalusC