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