Struts2_文件下载
来源:互联网 发布:seo 工程师 编辑:程序博客网 时间:2024/06/13 16:04
第一步:xml配置
<action name="download" class="action.netDiskAction.DownloadAction">
<!-- 文件名 -->
<param name="fileName"></param>
<result name="success" type="stream">
<!-- 类型-->
<param name="contentType">text/plain</param>
<!-- 前台链接参数 -->
<param name="contentDisposition">attachment;filename="${downloadChineseFileName}"</param>
<param name="inputName">downloadFile</param>
</result>
<result name="downloaderror" type="chain">showResList</result>
</action>
第二步: 类的实现
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 个人中心资源问答下载附件实现
*/
public class DownloadAction extends ActionSupport {
private String fileName; // 文件名和文件路径
private String newFileName; // 用于下载后显示的文件名
private boolean isExists; // 用户判断文件是否存在
private int toPage; // 下载资源所在的当前页面
// 从下载文件原始存放路径读取得到文件输出流
public InputStream getDownloadFile() {
return ServletActionContext.getServletContext().getResourceAsStream("/" + fileName);
}
// 如果下载文件名为中文,进行字符编码转换
public String getDownloadChineseFileName() {
String downloadChineseFileName = newFileName;
try {
downloadChineseFileName = new String(downloadChineseFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downloadChineseFileName;
}
public String execute() {
String basePath = ServletActionContext.getServletContext().getRealPath("");
String filePath = basePath + fileName;
File file = new File(filePath);
if (!file.exists()) {
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("message", "文件已经不存在,请联系管理员!");
// 如果topage为0时,说明在第一页,需要进行重新设置为1
if (toPage == 0) {toPage = 1;}
return "downloaderror";
} else {
return SUCCESS;
}
}
public String getFileName() {return fileName;}
public void setFileName(String fileName) {this.fileName = fileName;}
public String getNewFileName() {return newFileName;}
public void setNewFileName(String newFileName) {this.newFileName = newFileName;}
public int getToPage() {return toPage;}
public void setToPage(int toPage) {this.toPage = toPage;}
}
- Struts2_文件下载
- struts2_文件下载
- Struts2_文件下载
- 27.struts2_文件的下载
- Struts2_文件上传_Demo
- struts2_文件上传下载
- Struts2_单文件上传
- Struts2_多文件上传
- struts2_文件上传
- Struts2_文件上传
- Struts2_事物管理&文件上传
- Struts2_事物管理&文件上传
- 42. Struts2_文件的上传
- 26.struts2_文件的上传
- struts2_大纲08_文件上传下载
- Struts2_配置包范围国际化资源文件
- Struts2_学习笔记(一)--------学习工具下载、HelloWorld、运行机制
- Struts2_学习笔记(一)--------学习工具下载、HelloWorld、运行机制
- jQuery_选择器
- 引用DLL打包出错”But the dll is not allowed to be included or could not be found.“
- postman测试文件上传
- struts1和struts2区别
- JUnit_setup()和teardown()
- Struts2_文件下载
- GridView仿微信添加多图效果
- Java_Dom4j_解析xml
- DB2入门(2)——数据库、实例、存储模型
- FreeMarker_web.xml
- 面试的题目
- FreeMarker_whatis
- FreeMarker_quick start
- Countdown Latches