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 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

<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/</param>
		<param name="inputName">fileInputStream</param>
		<param name="bufferSize">1024</param>

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 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.

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

Related Article

On running this application

Read More