ResourceDownloadAction.java
package csu.soft.boss.action;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class ResourceDownloadAction implements Action {
private String inputPath; //服务器端文件名
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
private String fileName; //客户端下载保存文件名
public String getFileName() throws UnsupportedEncodingException {
String downFileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
downFileName=URLEncoder.encode(downFileName,"UTF-8");
return downFileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
private int flag;
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
// inputStream属性的getter方法,StreamResult结果类型使用该属性来读取下载文件的内容
public InputStream getInputStream() throws Exception{
//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
String filePath="";
if(flag==1){
filePath=ServletActionContext.getServletContext().getRealPath("/ProjectAttachments/")+"\\"+inputPath;
}else if(flag==2){
filePath=ServletActionContext.getServletContext().getRealPath("/BaseAttachments/")+"\\"+inputPath;
}else if(flag==3){
String postfix=inputPath.substring(inputPath.indexOf("."));
fileName=fileName+postfix;
filePath=ServletActionContext.getServletContext().getRealPath("/Resources/")+"\\"+inputPath;
}
return new FileInputStream(filePath);
}
public String execute() throws Exception {
return SUCCESS;
}
}
struts.xml
<action name="ResourceDownloadAction" class="csu.soft.boss.action.ResourceDownloadAction">
<!-- 使用StreamResult结果类型 -->
<result name="success" type="stream">
<!-- inputName默认值是inputStream,如果action中用于读取下载文件内容的属性名是inputStream,那么可以省略这个参数 -->
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
<param name="bufferSize">
2048
</param>
</result>
</action>
projectInfo.jsp
<a href="ResourceDownloadAction?inputPath=${file.savedName}&fileName=${file.realName}&flag=1">${file.realName}</a>