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.multipart.maxSize" value="10701096"/>
<constant name="struts.devMode" value="true" />
<package name="lhy" namespace="/lhy" extends="struts-default">
<action name="download" class="action.FileDownLoad" method="downLoad">
<!--
(1) <param name="contentDisposition">attachment;fileName="${fileName}"</param>
contentDisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,
就直接在网页上打开,不能直接打开的才会打开下载框自己选择
(2)<param name="contentDisposition">attachment;filename="${fileName}"</param>
attachment :下载时会打开下载框
fileName="${fileName}" :在这定义的名字是一个动态的,在value stack中
(3) <param name="inputName">lhydownload</param>,这个downloadFile名字要和
FileDownload.java类中的getLhydownload()方法名去掉get 一致
(4)bufferSize 下载缓冲区的大小
-->
<result type="stream" name="download">
<param name="contentType">application/octet-stream</param>
<!-- 要有相对应的getDownloadFile()方法返回值是 InputStream -->
<param name="inputName">lhydownload</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
FileDownLoad.java
package action;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownLoad extends ActionSupport{
private String fileName;
public String downLoad()
{
//此方法不尽兴任何操作,只有返回值
return "download";
}
public InputStream getLhydownload()
{
//声明输入流
InputStream is = null;
String filePath=ServletActionContext.getServletContext().getRealPath("/upload");
System.out.println(filePath);
System.out.println(fileName);
try {
is = new FileInputStream(filePath+"/"+fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(is);
return is;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
jsp
<a href="/struts_uploadFile_download/lhy/download.action?fileName=20150923184827.jpg">下载</a>