Monday, August 30, 2010

File download using Struts

In some developments, you have to prompt "OPEN/SAVE" dialog for file viewing.
Here is a sample code for file download with the support of the "DownloadAction".

import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;


public class ExampleByteArrayDownload extends DownloadAction {

    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
   
        String fileName = httpServletRequest.getParameter("fileName");

        String fileExtension =
            fileName.substring(fileName.lastIndexOf("."), fileName.length());

        httpServletResponse.setHeader("Content-Disposition",
                                      "attachment;filename=\"" + fileName +
                                      "\"");
        
        // Download a "pdf" file
        String contentType = "application/pdf";
        byte[] myPdfBytes  = null;              // Get the bytes from somewhere

        return new ByteArrayStreamInfo(contentType, myPdfBytes);
        
    }

    protected class ByteArrayStreamInfo implements StreamInfo {
        
        protected String contentType;
        protected byte[] bytes;
        
        public ByteArrayStreamInfo(String contentType, byte[] bytes) {
            this.contentType = contentType;
            this.bytes = bytes;
        }
        
        public String getContentType() {
            return contentType;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }
}

Reference
http://wiki.apache.org/struts/StrutsFileDownload