tags:

views:

442

answers:

3

I know this is a little broad, but here's the situation:

I am using JSP and Java. I have a file located on my server. I would like to add a link to the screen that, when clicked, would open the file for the user to view. The file can either appear in a window in the web browser, or pop up the program needed to open the file (similar to when you are outputting with iText to the screen, where Adobe opens to display the file). I know my output stream already, but how can I write the file to the output stream? Most of what I have read has only dealt with text files, but I might be dealing with image files, etc., as well.

Any help is appreciated! Thanks!

+1  A: 

You need to create a 'download' servlet which writes the file to the response output stream with correct mime types. You can not reliably do this from within a .jsp file.

We usually do it with a 'download servlet' which we set the servletmapping to /downloads, then append path info to identify the asset to serve. The servlet verifies the request is valid, sets the mime header then delivers the file to the output stream. It's straightforward, but keep the J2EE javadocs handy while doing it.

caskey
+2  A: 

You need to add certain fields to the response. For a text/csv, you'd do:

 response.setContentType("text/csv"); // set MIME type 
 response.setHeader("Content-Disposition", "attachment; filename=\"" strExportFileName "\"");

Here's a forum on sun about it.

seth
A: 

Here's a simple implementation on how to achieve it:

protected void doPost(final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException,
        IOException {

    // extract filename from request
    // TODO use a whitelist to avoid [path-traversing][1]
    File file = new File(getFileName(request));
    InputStream input = new FileInputStream(file);

    response.setContentLength((int) file.length());
    // TODO map your file to the appropriate MIME
    response.setContentType(getMimeType(file));

    OutputStream output = response.getOutputStream();
    byte[] bytes = new byte[BUFFER_LENGTH];
    int read = 0;
    while (read != -1) {
        read = input.read(bytes, 0, BUFFER_LENGTH);
        if (read != -1) {
            output.write(bytes, 0, read);
            output.flush();
        }
    }

    input.close();
    output.close();
}
ignasi35