Monday, May 28, 2012

How to Implement File Download in JAVA

The files that appear on your web-app are part of the JSP and HTML pages. If you want to download them, you need to make a request to the servlet. The servlet reads the bytes of the files from an input stream, and writes them to the output stream. The output stream is nothing but a ServletOutputStream suitable for writing binary data in the response.

Check out the following code snippet:


BufferedOutputStream out =  new BufferedOutputStream(response.getOutputStream());

File f = new File("Path of the file on the server");
InputStream is = new FileInputStream(f);
BufferedInputStream in = new BufferedInputStream(is);
response.setHeader( "Content-Disposition", "attachment; filename=somefile.txt");
byte [] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer))>0){
    out.write(buffer, 0, bytesRead);
}

is.close();
in.close();
out.close();


Since you need the response as an attachment to the browser, you need to set the response header accordingly as follows:

response.setHeader("Content-Disposition", "attachment; filename=somefile.txt"; 

No comments:

Post a Comment