Download Varbinary in a JSF webapp

I recently had to read a varbinary (sql server 2005) and download it from my JSF application…

Here is a method to do so, it recieves the file nameĀ  (string), the content (byte[]) and file extention (string).

Add this to the import section:

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
public static void downloadVarbinary(String fileName,
            byte[] content, String extention) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext
                    .getCurrentInstance().getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse
                    .getOutputStream();
            httpServletResponse.setHeader("Content-disposition",
                    "attachment; filename=" + fileName + "." + extention);
            httpServletResponse.setContentLength((int) content.length);
            httpServletResponse.setContentType("application/x-download");
            servletOutputStream.write(content);
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Advertisements