1. struts.xml
<action name="download" class="com.tvunetworks.center.tpc.util.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="hello.txt"</param>
<param name="bufferSize">4096</param>
</result>
</action>
notice: <param name="contentDisposition">attachment;filename="${filename}"</param>
2.Action
package com.tvunetworks.center.tpc.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class DownloadAction {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
//如果名字使用了$
private String filename;
public String getFilename(){
return filename;
}
public String execute() throws FileNotFoundException{
inputStream=new FileInputStream(new File("C:\\a.txt"));
/* filename="C:\\a.txt";
* inputStream=new FileInputStream(new File(filename));
*/
return "success";
}
}
3. 在URL输入:http://127.0.0.1:8080/myapp/download.action即能下载。
4、也可以下载自己在java写入的字符串,如下面的代码就能下载文件内容为my test的文件。
public String execute() throws FileNotFoundException{
Strinig str="my test";
inputStream=new ByteArrayInputStream(enStr.getBytes());
return "success";
}