Saturday, March 13, 2010

how to use "Content-Disposition" for file download via http(s)/ftp server

Content-Disposition Header Field
This is an optional field. Never thought this could save my ass.
It has a wonderful param "filename" thru which we can out the content of the file to be downloaded. If you don't use it, the file will download with the servlet name.
Ex: /fyi/myservlet.do
While downloading the file, the dialog prompts to save file with myservlet.do which is really odd & when ur downloading a zip file the name says "save file myservlet.do"

If you dont understand any (:-) thing above see the below code.

response.setHeader("Content-Disposition", "attachment; filename="+ filename);

URL url = new URL("https://fyi/downloadfile/filename.zip");
conn = (HttpsURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
response.setContentType(conn.getContentType());
response.setContentLength(conn.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename="
+ filename);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while ((size = in.read(buf)) >= 0) {
out.write(buf, 0, size);
}
in.close();
out.close();
}

try urself.

to know more about content-disp..

No comments: