STEP 1. Make a link in JSP
<li>
<a href="export_perform.action" mce_href="export_perform.action">
Export file
</a>
</li>
STEP 2. Define the action in Struts.xml with input name property
<action name="export_*" method="{1}" class="com.actions.ExportAction">
<result name="download" 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>
STEP 3. Make an action method in Action Class (ExportAction.java)
FileInputStream fileInputStream;
// getter and setter of fileInputStream property
public String execute() {
// Generate and write to file
String filePath = "C:\\abc.txt";
FileWriter fileWriter;
try {
fileWriter = new FileWriter(new File(filePath));BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);bufferedWriter.write("content line-1");bufferedWriter.newLine();bufferedWriter.write("content line-2");
} catch(Exception e) { }
bufferedWriter.flush();
fileWriter.flush();
bufferedWriter.close();
fileWriter.close();
// Set the stream in property to be downloaded
try {
fileInputStream = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "download"; // return the stream result
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.