A Struts 2 example to show the use of custom result type to allow user to download file.

1. Action

In Action class, declared an InputStream data type and its getter method.


package com.mkyong.common.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport{
	private InputStream fileInputStream;
	public InputStream getFileInputStream() {
		return fileInputStream;
	public String execute() throws Exception {
	    fileInputStream = new FileInputStream(new File("C:\\downloadfile.txt"));
	    return SUCCESS;

2. View page

A normal page, with a download link to download a file.


<%@ taglib prefix="s" uri="/struts-tags" %>
<h1>Struts 2 download file example</h1>
<s:url id="fileDownload" namespace="/" action="download" ></s:url>
<h4>Download file - <s:a href="%{fileDownload}">fileABC.txt</s:a>

3. struts.xml

Define the download file detail, self-explanatory. The <param name=”inputName”> value is the name of the InputStream property from the Action.

Read this Struts 2 Stream Result documentation for more detail explanation.


<?xml version="1.0" encoding="UTF-8" ?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
   <action name="">
	<result name="success">pages/downloadPage.jsp</result>
   <action name="download" class="com.mkyong.common.action.DownloadAction">
	<result name="success" type="stream">
	  <param name="contentType">application/octet-stream</param>
	  <param name="inputName">fileInputStream</param>
	  <param name="contentDisposition">attachment;filename="fileABC.txt"</param>
	  <param name="bufferSize">1024</param>

4. Run it


Struts2 download file example


  1. http://struts.apache.org/2.x/docs/stream-result.html
  2. http://www.iana.org/assignments/media-types/
  3. http://www.mkyong.com/struts/struts-download-file-from-website-example/
  4. http://www.mkyong.com/java/how-to-download-file-from-website-java-jsp/
  5. http://struts.apache.org/2.x/docs/how-can-we-return-a-text-string-as-the-response.html
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts