import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/*//拦截器
@InterceptorRef(value = "downloaddefault")*/
public class FileDownloadAction extends CftsBaseAction {
private static final long serialVersionUID = 5837877107118611942L;
private String attachid;//附件id
private String message;
private String fileName;// 初始的通过param指定的文件名属性
// private ContentAttach contentAttachs;//附件对象
/**
* 文件下载
*/
@Override
@Action(value="downLoad",
results={@Result(name = "download", type = "stream", params = {
"contentType", "application/octet-stream",
"inputName", "inputStream", "contentDisposition",
"attachment;filename=\"${fileName}\"", "bufferSize",
"4096" }),@Result(name = "fileNotExist",location="Test02.jsp")}
)
public String execute() {
fileName = "loginbg.jpg" ;
try {
setFileName(fileName);
String aa = downloadFile();
if (!aa.equals("")) {
return aa;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "download";
}
public String downloadFile(){
//判断下载文件是否存在
message = "sorry,file is not exist";
return "fileNotExist";
}
return "";
}
public InputStream getInputStream() throws Exception{
//String root = FilePathSptUtil.UPLOAD_ROOT_PATH;
// String url=root+contentAttachs.getAttachUrl();
//return new FileInputStream(new File(url));
//inputPath ="/images/fz01_dis.png";
//获取资源路径
//测试用路径可以从property中取得文件路径
return ServletActionContext.getServletContext().getResourceAsStream("/images/loginbg.jpg") ;
//return new FileInputStream(new File(inputPath));
//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}
public void setFileName(String fileName) throws UnsupportedEncodingException {
String agent = ServletActionContext. getRequest().getHeader("User-agent");
//如果浏览器是IE浏览器,就得进行编码转换
if(agent.contains("MSIE")){
this.fileName = URLEncoder.encode(fileName, "UTF-8");
}else{
this.fileName = new String(fileName.getBytes(),"ISO-8859-1");
}
}
public String getAttachid() {
return attachid;
}
public void setAttachid(String attachid) {
this.attachid = attachid;
}
public String getFileName() {
return fileName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}