Pages Navigation Menu

Coding is much easier than you think

File Download Example in Struts 2

Posted by on Sep 29, 2013 in Struts 2 Tutorial, Struts-2 | 3 comments

 
This tutorial will help you understanding how to create a Struts 2 action class that allows users to download files from server to their local computer.
 
struts.xml
 
Struts 2 provides a custom result type called “stream” that performs file download by “streaming” an InputStream of a file to the client through the HttpServletResponse. Here’s an example that shows how to define this result type element in struts.xml:
 
The struts.xml file should have the following mapping

<struts>
<package name="default" namespace="/jsp" extends="struts-default">

	<action name="download" class="com.simplecode.action.DownloadAction">
	<result name="success" type="stream">
		<param name="contentDisposition">attachment;filename=${fileName}</param>
		<param name="contentType">application/vnd.ms-excel</param>
		<param name="inputName">fileInputStream</param>
		<param name="bufferSize">1024</param>
	</result>
	</action>
</package>
</struts>

 
Note that we declare a property placeholder called “fileName” which will be dynamically updated by Struts. Now in the action class, we need to declare a variable with the same name along with getter and setter method. By this way we have configured the download file name dynamically.
 
In addition to that, we must define an InputStream object which has the same name as the name specified by the inputName parameter in struts.xml. All the variables must have appropriate getter methods.
 
Recommended Article

 

Action Class

 

package com.simplecode.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.opensymphony.xwork2.Action;

public class DownloadAction implements Action 
{
	private InputStream fileInputStream;
        // Used to set file name dynamically
	private String fileName;
	
	public InputStream getFileInputStream() 
	{
		return fileInputStream;
	}

	public String execute() throws Exception 
	{
                File fileToDownload = new File("C:/Download/MyFile.xls");
	        fileName = fileToDownload.getName();
		fileInputStream = new FileInputStream(fileToDownload);
		return SUCCESS;
	}

	public String getFileName() 
	{
		return fileName;
	}

	public void setFileName(String fileName) 
	{
		this.fileName = fileName;
	}	
}

 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Jsp
 

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<title>File Download</title>
<body>
<h3>Struts 2 file download example</h3>
  <s:url id="fileDownload" namespace="/jsp" action="download"></s:url>
   <h4>
     Download file - <s:a href="%{fileDownload}">MyFile.xls</s:a>
   </h4>
</body>
</html>

 
Related Article

Demo
 
On running this application
Download
 

Read More