一、 JSP页面
<a href="download.action?fileName=Koala.jpg">点击下载图片</a>
二、struts.xml配置文件中
<action name="download" class="action.DownloadAction">
<param name="inputPath">/upload</param>
<result name="success" type="stream" >
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=Koala.jpg</param>
<param name="bufferSize">4096</param>
</result>
</action>
三、 DownloadAction类
public class DownloadAction {
// 读取下载文件的输入流
private InputStream inputStream;
// 读取下载文件的目录
private String inputPath;
// 下载文件的文件名
private String fileName;
public String execute() throws Exception {
return "success";
}
// 创建InputStream的输入流
public InputStream getInputStream() { String path = ServletActionContext.getServletContext().getRealPath(
inputPath);
System.out.println("===" + path + "\\" + getFileName());
try {
return new BufferedInputStream(new FileInputStream(path + "\\"
+ fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
return null;
}
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}