struts2 下的文件下载
推荐:Struts 2中实现文件下载(修正中文问题)http://lichen.blog.51cto.com/697816/153753
本网址中解释了配置文件的各个参数的含义
?
?
package utils;
import java.io.File;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class DownLoadAction extends ActionSupport {
?
?private String fileName; // 文件名参数变量
?
?private String filePath; // 文件路径
?
?private String parameter; // 其他参数
?// 从下载文件原始存放路径读取得到文件输出流
?public InputStream getDownloadFile() {
??
??return ServletActionContext.getServletContext().getResourceAsStream(filePath);
?}
?
?// 如果下载文件名为中文,进行字符编码转换
?public String getDownloadChineseFileName(){
??
??String downloadChineseFileName = fileName;
???try {
???? downloadChineseFileName = new String(downloadChineseFileName.getBytes(), "ISO-8859-1");
???} catch (Exception e) {
????return ERROR;
???}
???return downloadChineseFileName;??
???
?}
?public String execute() {
??
??String basePath = ServletActionContext.getServletContext().getRealPath("");
??
??String newFilePath = basePath + filePath;
??
??File file = new File(newFilePath);
??
??if (!file.isFile()||!file.exists()) {
??
???HttpServletRequest request = ServletActionContext.getRequest();
???request.getSession().setAttribute("message", "文件已经不存在,请联系管理员!");
???
???return "downloaderror";
??
??} else {
???return SUCCESS;
??}
??
?}
?
?public String getFileName() {
??return fileName;
?}
?public void setFileName(String fileName) {
??this.fileName = fileName;
?}
?public String getFilePath() {
??return filePath;
?}
?public void setFilePath(String filePath) {
??this.filePath = filePath;
?}?
?public String getParameter() {
??return parameter;
?}
?public void setParameter(String parameter) {
??this.parameter = parameter;
?}
}
/**
???? <!-- 下载文件配置 如下 -->
????????? <action name="downLoadFile" type="stream">
?????<param name="contentType">application/vnd.ms-word</param>????
?????<param name="contentDisposition">filename="${downloadChineseFileName}"</param>
?????<param name="inputName">downloadFile</param>
????</result>
????<result name="downloaderror" type="redirectAction" >
?????? showViewGrowupInfo.action?growupInfoId=${parameter}
????</result>
????????? </action>
?? 调用下载链接 如下:
??? <a href="${pageContext.request.contextPath }/personcenter/growinfo/downLoadFile.action?filePath=${growUpFile.fileAddress}&fileName=${growUpFile.fileName}¶meter=${growUpinfo.growupInfoId}" >下载</a>
*/