Search This Blog

Wednesday, February 24, 2010

Java Code to download attachments or any file from the database

Recently I got a requirement to save attachments into database and download it from UI (Inbox like yahoo or google ). And download attachment which received with the message , I did some research and write following java code as below to implement :

// content from BLOB
BlobDto dto = model.getFileContent();

// set header type
servletResponse.setHeader("Pragma", "");
servletResponse.setHeader("Cache-Control", "");
servletResponse.setHeader("Content-disposition",
"attachment; filename=" + model.getFileName());

// need to do proper content type , a check for content type
if (model.getFileType().equals("pdf"))
{
servletResponse.setContentType("application/pdf");
}
else if (model.getFileType().equals("xls")
|| model.getFileType().equals("csv"))
{
servletResponse.setContentType("application/vnd.ms-excel");
}
else
{
servletResponse.setContentType("application/octet-stream");
}

InputStream is = null;
try
{
OutputStream os = servletResponse.getOutputStream();
is = dto.getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf, 0, buf.length)) > 0)
{
os.write(buf, 0, len); // will give download window to save attachment
}
}
catch (FileNotFoundException e)
{
logger.error(e);
}
catch (IOException e)
{
logger.error(e);
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
logger.error("Failed to close InputStream", e);
}
}
}

No comments:

Post a Comment

Thanks for your comment, will revert as soon as we read it.

Popular Posts