2 Replies Latest reply on Sep 16, 2007 11:40 PM by Humber

    Downloading Files

    Stuart Douglas Master

      At the moment to create a file download in SEAM it looks like you have to implement a custom servlet / filter. I was thinking it would be neat if you could just annotate an action method with an @ContentType("mimetype") annotation and return a byte array, and have seam take care of the rest?

        • 1. Re: Downloading Files
          Shane Bryzak Master

          Actually you can do something similar, you can just create a Seam component that extends org.jboss.seam.web.AbstractResource and implement the getResource() and getResourcePath() methods. Take a look at org.jboss.seam.captcha.CaptchaImage for an example.

          • 2. Re: Downloading Files
            Humber Newbie

            Put this action in some Seam component.

            <s:link action="{someSeamComponent.download}" value="Download"/>

            And the action in SomeSeamComponent

            public void download() {
             //Here you get the entity that has a byte array with the data
             SomeEntity entity = getEntityFromEntityManager();
            
            
             FacesContext facesContext = FacesContext.getCurrentInstance();
             HttpServletResponse response = (HttpServletResponse) facesContext
             .getExternalContext().getResponse();
             response.setContentType(entity.getContentType());
            //Asume a data property inside entity
             byte[] data = entity.getData();
             response.setContentLength(data.length);
             response.setHeader("Content-disposition", "inline; filename=\""
             + entity.getFileName() + "\"");
            
             try {
            
             OutputStream out = response.getOutputStream();
            
             out.write(data);
            
             out.flush();
             out.close();
            
             facesContext.responseComplete();
             } catch (IOException ex) {
             FacesMessages.instance().add(
             "Error while downloading the file: " + entity.getFileName());
             }
            
             }
            
            


            Cheers