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.

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>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2836379775501347"
     data-ad-slot="8821506761"
     data-ad-format="auto"
     data-ad-region="mkyongregion"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>Download file - <s:a href="%{fileDownload}">fileABC.txt</s:a>
</h2>
	
</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

About the Author

author image
mkyong
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.

Comments

Leave a Reply

avatar
newest oldest most voted
Bundi
Guest
Bundi

Dear MKYong.. all your articles related to Java technologies are really helpful to many across the globe. Thank you very much!!

Binh Thanh Nguyen
Guest
Binh Thanh Nguyen

Thanks, nice example

Arpit Gupta
Guest
Arpit Gupta

I am getting java.lang.illegalStateException when the client user clicks on download link with Third party download managers like IDM installed in system. IDM sends multiple requests simultaneously to download the content in chunks. Please help in how to resolve this exception. Even when user cancels from file download dialog box, it is throwing exception.

Nancy
Guest
Nancy

Hi, is it possible to display multiple images with struts2 inputstream

Palanirajan
Guest
Palanirajan

Hi,

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

Good one, Worked for me….

victor
Guest
victor

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

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

did it using getter in the action class.

public String getContentDisposition() {
return contentDisposition;
}

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

anand
Guest
anand

all the questions I had today are answered by you.

manu
Guest
manu

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

Gema Luhring
Guest
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
Guest
Dipak C
Hi, I am getting following error. Please help my java action File tempfile=File.createTempFile("testfile", ".xls"); FileOutputStream xlsStream = new FileOutputStream(tempfile); if(Constants.DEBUG) System.out.println("tempfile:"+tempfile.getAbsolutePath()); Json2Excel.build(xlsStream, json, colStr.split(","), colStr.split(",") ); // bos.close(); xlsStream.close(); fileInputStream =new FileInputStream(tempfile); return "export"; NOTE: check manually that file is created with the required data at temp location. My struts result xml <action name="lectureAttendanceListJson" class="com.cypruss.elearning.webapp.action.ReportsAction" method="lectureAttendanceListJson"> <result name="success" type="json"> <param name="ignoreHierarchy">false</param> <param name="excludeNullProperties">false</param> </result> <result name="export" type="stream"> <param name="contentType">application/octet-stream</param> <param name="inputName">fileInputStream</param> <param name="contentDisposition">attachment;filename="testjqgrid.xls"</param> <param name="bufferSize">1024</param> </result> </action> my HTML Javascript calling the action as Ajax function exportData( griddata) { //var params = $.toJSON(this.p.postData); $.ajax({ type:"GET" ,url: 'lectureAttendanceListJson.html' ,data:'export=xls' ,cache:false ,success:… Read more »
anudeep
Guest
anudeep

Hi,

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 .

trackback
Struts2 Jasper Rerports Plugin « Track 4 J

[…] http://www.mkyong.com/struts2/struts-2-download-file-example/ Categories: Java, Plugin, struts2 Tags: attachment, download, dynamic, in line, inline, jasper, java, plugin, report, reporting, reports, result type, return type, stream, struts, struts2 LikeBe the first to like this post. Comments (0) Trackbacks (0) Leave a comment Trackback […]