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.

DownloadAction.java

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.

downloadPage.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
 
<body>
<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>
</h4>
 
</body>
</html>

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.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
 
<constant name="struts.devMode" value="true" />
 
<package name="default" namespace="/" extends="struts-default">
   <action name="">
	<result name="success">pages/downloadPage.jsp</result>
   </action>
 
   <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>
	</result>
   </action>
</package>
 
</struts>

4. Run it

http://localhost:8080/Struts2Example/

Struts2 download file example

Reference

  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
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
[ Read More ] You can find more similar articles at Struts 2.x Tutorials