Struts 2 Download file example- How to configure the file name dynamically?

Struts2Logo

In this tutorial, i am going to show you how to download file in struts 2 using custom result type configured in struts.xml.
jsp page code with download link to download a file.
downloadFile.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>

<h1>Struts 2 download file exampleh1>

<s:url id="downloadFile" action="downloadFile">s:url>
<s:a href="%{downloadFile}" title="Download File">Click here to dowload files</s:a>


struts.xml
ThefileInputStreamparam> value i.e. fileInputStream  is the name of the InputStream property from the Action class and inattachment;filename="${fileName} , ${fileName} where fileName is same fileName property from the Action class.


<?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" extends="struts-default">
<action name="downloadFile" class="com.jk.downloadAction" method="downloadFile">
<interceptor-ref name="fileUpload">
<param name="maximumSize">5048000000</param>
<param name="allowedTypes">text/plain</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>

</struts>


DownloadAction.java
public class DownloadAction
{
private InputStream fileInputStream;
private String fileName;
public String writeErrorFile(final Map errorMap) throws IOException {
setFileName("file.txt");
StringBuffer buffer = new StringBuffer();
buffer.append("Content to show");
fileInputStream = new ByteArrayInputStream(buffer.toString().getBytes());

return SUCCESS;
}
public InputStream getFileInputStream() {
return fileInputStream;
}
public String getFileName() {
return fileName;
}
pulic void setFileName(String fileName) {
this.fileName = fileName;
}
}

References:
1. http://struts.apache.org/development/2.x/docs/stream-result.html
2.http://struts.apache.org/development/2.x/docs/how-can-we-return-a-text-string-as-the-response.html

Share on Google Plus

About JK STACK

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

1 comments:

  1. Nice one .. it really helped as i was stuck in the exact situation where i wanted to provide name of my excel file thats getting downloaded .. thanks for sharing

    ReplyDelete