Where can I find some example source code for transfering arbitrary files to the client browser using JSP?

André Wolf

You should use a servlet instead of a JSP for this task. The following code copies a file from the server's hard disc to the output stream of the servlet (downloading a file).

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

public void DownloadServlet extends HttpServlet

  public String doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    int length;
    byte[] buf = new byte[1024];
    BufferedInputStream in =
        new BufferedInputStream(new FileInputStream(file path));
    ServletOutputStream out = 

    response.setContentType(mime type of the file);
    response.setContentLength(file size);
    // see http://www.faqs.org/rfcs/rfc1806.html
    response.addHeader("Content-Disposition", "inline; filename="" +
                file name + """);

    // copy data
    while ((in != null) && ((length = in.read(buf)) != -1))
      out.write(buf, 0, length);
The Content-Disposition header allows you to transmit the file name to the browser.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact