Struts DownloadAction

The org.apache.struts.actions.DownloadAction class can be used to download any file or stream from server. You need to extend org.apache.struts.actions.DownloadAction and implement the getStreamInfo() method. Optionally you can also override the getBufferSize() method if you require a different buffer size from the default. The DownloadAction, by default, returns a buffer size of 4096.

1. Action Class

Let us create an Action class that will handle the request.

package com.kruders.action;
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 Download extends DownloadAction{
    protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String contentType = "text/plain";
        File file = new File("C:\\helloworld.txt");
        response.setHeader("Content-disposition", "attachment; filename="+ "helloworld.txt");
        return new FileStreamInfo(contentType, file);

2. Action Handler

The next step is to create an action mapping for this action handler.

<action path="/downloadFile"
    type="com.kruders.action.Download" scope="request">

In this above configuration you also can add the parameter attribute, where you can specify the file full path which has to be downloading.

3. Create JSP file

Now create download.jsp and write the following code.

<%@ taglib uri="" prefix="html"%>
<%@ taglib uri="" prefix="html"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts DownloadAction</title>
<html:link action="/downloadFile">Click here to Download</html:link>

4. Run Project

Now when you run the project, following screen will be displayed as in Figure 13.1

Figure 13.1 Figure 13.1

Now when you click download link, following screen will be displayed as in Figure 13.2

Figure 13.2 Figure 13.2

The folder structure of the example is shown below in Figure 13.3

Figure 13.3 Figure 13.3

You can download the source code of this example here.

One Response to Struts DownloadAction