Stream Result is very important for allowing users to downloading contents. It is a custom result type for sending raw data via InputStream to the HttpServletResponse. It has the following parameters.
contentType- It is the MIME type which is sent on the browser.
inputName- It is the name of the input stream property.ADS_TO_REPLACE_1
contentLength - It is the Stream length in byte.
bufferSize- It is the size of the buffer to copy from input to output.
allowCaching - Its default value is true. If allowCaching set to false then it will set the Header "Pragma" and Cache-Control to "No-Catche".ADS_TO_REPLACE_2
contentDisposition - It is used for specifying file name.
An Example of Stream Result is given below
page.jspADS_TO_REPLACE_3
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Chain Result Example</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <font color="megenta" size="6" face="Comic Sans MS">Stream Result example</font><br clear="all"/><br clear="all"/> <s:url action="download" id="copy"></s:url> <strong><font color="green" size="5" face="arier">Click on <s:a href="%{copy}">file</s:a> to Download</font></strong> </body> </html>
StreamResultExample.java
package net.roseindia; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import com.opensymphony.xwork2.ActionSupport; public class StreamResultExample 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; } }
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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <package name="roseindia" extends="struts-default"> <action name="resultStream"> <result name="success">/jsp/page.jsp</result> </action> <action name="download" class="net.roseindia.StreamResultExample"> <result name="success" type="stream"> <param name="contentType">application/octet-stream</param> <param name="inputName">fileInputStream</param> <param name="contentDisposition">attachment;filename="testFile.txt"</param> <param name="bufferSize">1024</param> </result> </action> </package> </struts>
Now Save a text file named downloadfile.txt in the C:\\downloadfile.txt.
And then Run The Application Given BelowADS_TO_REPLACE_4
When you run this application it will display message as shown below:
Advertisements
Ads
Ads