JAVA Web 之 struts2文件上传下载演示(二)
一、文件上传演示
详细查看本人的另一篇博客 http://blog.csdn.net/red_titan/article/details/7843270
二、文件下载演示
1.Web界面
由于我的操作是,先上传文件,然后才能下载,所以,html代码中的fileFileName=${newFileName},而不是等于具体的文件名,大家在自己做项目的时候,可以修改一下
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="<%=basePath%>">
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>下载文件</title>
- </head>
- <body>
- <div align="center">
- <a href="download?fileFileName=${newFileName}">下载</a>
- </div>
- </body>
- </html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载文件</title>
</head>
<body>
<div align="center">
<a href="download?fileFileName=${newFileName}">下载</a>
</div>
</body>
</html>
2.Struts配置
- <action name="download" class="action.FileAction" method="download">
- <result name="success" type="stream">
- <param name="contentType">application/octet-stream</param>
- <!-- filename的属性值,表示的是下载的时候,显示在下载工具中的文件名,而不一定是保存的文件的文件名 -->
- <param name="contentDisposition">attachment;filename="${fileFileName}"</param>
- <!-- 下载的文件流的方法名, 也就是说, 在Java代码里面必须有InputStream getDownloadFile()这个方法 -->
- <!-- 在这里定义成文件名xxx,那么对应在Java文件中就必须要有InputStream getXxx()方法 -->
- <param name="inputName">downloadFile</param>
- <!-- 缓存大小 -->
- <param name="bufferSize">4096</param>
- </result>
- <result name="input">index.jsp</result>
- </action>
3.Java后台代码
- public String download(){
- return SUCCESS;
- }
- public InputStream getDownloadFile() {
- return ServletActionContext.getServletContext().getResourceAsStream(
- "/file/" + fileFileName);
- }
public String download(){
return SUCCESS;
}
public InputStream getDownloadFile() {
return ServletActionContext.getServletContext().getResourceAsStream(
"/file/" + fileFileName);
}
4.小注
至此,文件下载演示完成
下载的效果图如下所示