Thursday 13 March 2008

How to write a servlet that downloads the file saved as blob in database?

When we store any file in database in the blob column, we would also want it to be downloaded as and when required by webpage.

To achieve this we can write a servlet or a action in Webwork that makes this facility available. In the servlet we write the jdbc code to get the blob column in bytes[] format. Once we have file content in bytes[] we can add it to the response using OutputStream. Also if we want to give a name to file we can set the header in the response. Following is the code which will show how to do this.

----------- jdbc code to get the blob column ---------

bytes[] content= //get the blob using jdbc or any persistent framework.

doService(ServletRequest req, ServletResponse res){

HttpServletResponse response=(HttpServletResponse)res ;

response.setContenType("application/doc");

response.addHeader("Content-Disposition", "attachment; filename=file.doc"

ServletOutputStream output = response.getOutputStream();

output.write(content);

}

No comments: