Struts 2 download file example

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


Tags :

About the Author

Founder of and, 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.


  • Pingback: ionizer loans()

  • Pingback: payment plan()

  • Pingback: water ionizer()

  • Pingback: 10 famous electricians()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrków trybunalski()

  • Pingback: paypal loans()

  • Pingback: plumbing supply near 30052()

  • Pingback: read the full info here()

  • Pingback: 539 locksmiths()

  • Pingback: level 1 electrician jobs()

  • Pingback: water ionizer plans()

  • Pingback: pay per day loan plans()

  • Pingback: parking()

  • Pingback: laan penge nu uden sikkerhed()

  • Pingback: car parking()

  • Pingback: Grandpas tear up youthful modern nurse()

  • Pingback: free movie downloads()

  • Pingback: watch tv show episodes()

  • Pingback: Blue Coaster33()

  • Palanirajan


    your all examples are very helpful..
    it’s possible redirect page once streaming done? and how to handle the exception during download process in struts 2?

    Thanks in advance

  • Vrushali

    Good one, Worked for me….

  • http://none victor

    Debo reconocer que me ayudo mucho tu codigo, muchas gracias……

  • anand

    is it possible to make the downloadable file dynamic? In the xml we give the name of the file, can it be passed through action to the xml?

    • anand

      did it using getter in the action class.

      public String getContentDisposition() {
      return contentDisposition;

      contentDisposition = “attachment;filename=\”IMG_1448.JPG\””;

  • anand

    all the questions I had today are answered by you.

  • manu

    if i use the same program for display by changing the content type, i cant resize the image.
    can u tell me how to view all the images in a folder and resize them to my requirements.

  • http://þÿ Gema Luhring

    A person necessarily help to make severely articles I might state. This is the very first time I frequented your web page and so far? I amazed with the analysis you made to make this particular post extraordinary. Wonderful job!

  • Dipak C

    I am getting following error. Please help

    my java action

    File tempfile=File.createTempFile(&quot;testfile&quot;, &quot;.xls&quot;);
    						FileOutputStream xlsStream = new FileOutputStream(tempfile);
    						if(Constants.DEBUG) System.out.println(&quot;tempfile:&quot;+tempfile.getAbsolutePath());, json, 
    		            	//  bos.close();
    		            	  fileInputStream =new FileInputStream(tempfile);
    return &quot;export&quot;;

    NOTE: check manually that file is created with the required data at temp location.

    My struts result xml

     &lt;action name=&quot;lectureAttendanceListJson&quot; class=&quot;com.cypruss.elearning.webapp.action.ReportsAction&quot; method=&quot;lectureAttendanceListJson&quot;&gt;
               &lt;result name=&quot;success&quot; type=&quot;json&quot;&gt;  
                    &lt;param name=&quot;ignoreHierarchy&quot;&gt;false&lt;/param&gt;  
                    &lt;param name=&quot;excludeNullProperties&quot;&gt;false&lt;/param&gt;  
           	 &lt;result name=&quot;export&quot; type=&quot;stream&quot;&gt;
    		  &lt;param name=&quot;contentType&quot;&gt;application/octet-stream&lt;/param&gt;
    		  &lt;param name=&quot;inputName&quot;&gt;fileInputStream&lt;/param&gt;
    		  &lt;param name=&quot;contentDisposition&quot;&gt;attachment;filename=&quot;testjqgrid.xls&quot;&lt;/param&gt;
    		  &lt;param name=&quot;bufferSize&quot;&gt;1024&lt;/param&gt;

    my HTML Javascript calling the action as Ajax

    function exportData( griddata)
    		    	//var params = $.toJSON(this.p.postData);
    		    	,url: 'lectureAttendanceListJson.html'
    		    	,success: function(data,status) {
    		    		if($(&quot;#iframeX&quot;)) $(&quot;#iframeX&quot;).remove();
    		    		  var elemIF = document.createElement(&quot;iframe&quot;);
    		    		  elemIF.src = data;
     = &quot;iframeX&quot;;
     = &quot;none&quot;;
    		    	,error:function (xhr, ajaxOptions, thrownError){
    		    	,complete: function (XMLHttpRequest, textStatus) {
    		    	 var headers = XMLHttpRequest.getAllResponseHeaders();
    		    	,beforeSend: function(xhr){
    		    	//xhr.setRequestHeader('Accept', 'text/html');
    		    	//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    		    	//xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST');

    NOTE: line ‘alert(data);’ in javascript show the response in alert box, which is xls file. but it not showing download file dialog.
    and in Eclipse console shows the following error.. Please Help

    error Console:

    2012-04-17 08:29:41.492::WARN: EXCEPTION The filename, directory name, or volume label syntax is incorrect
    at Method)
    at org.mortbay.resource.FileResource.getAlias(
    at org.mortbay.jetty.servlet.DefaultServlet.getResource(
    at org.mortbay.jetty.servlet.DefaultServlet.doGet(
    at javax.servlet.http.HttpServlet.service(
    at javax.servlet.http.HttpServlet.service(
    at org.mortbay.jetty.servlet.ServletHolder.handle(
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(
    at com.cypruss.webapp.filter.SessionFilter.doFilter(
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(
    at com.cypruss.webapp.filter.StaticFilter.doFilterInternal(
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(
    at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(

  • anudeep


    with the above example , how do we close the fileInputStream opened during the response.

    we are not closing the fileInputStream here , this will create problems . fileInputStream holds the lock to the file untill the next download of different file is rquested or the any other strem opens this file .
    also we cannot delete the file .

    • mkyong

      Is this caused locked at your end? Struts2 should handle it automatically.

      • anudeep

        will the strus2 release the fileInputStream instance once the streaming is done?

  • Pingback: Struts2 Jasper Rerports Plugin « Track 4 J()