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

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

Rendyon | 9:19 AM | 0 comments
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 example</h1>

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

struts.xml
The <param name="inputName">fileInputStream</param> value i.e. fileInputStream  is the name of the InputStream property from the Action class and in <param name="contentDisposition">attachment;filename="${fileName}</param> , ${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 this article :

0 comments:

 
Copyright © 2011. Find Updates - All Rights Reserved
Template Modify by Creating Website
Proudly powered by Blogger