JavaEE中struts2实现文件上传下载功能实例解析
作者:yungcs_ 时间:2023-03-09 07:54:31
本文实例为大家分享了struts2实现文件上传下载的具体实现代码,供大家参考,具体内容如下
一、文件上传
struts提交的文件组件上传,
前台:
1)、提交方式POST
2)、表单类型 multipart/form-data
3)、input type=file
后台:
Apache提供的FileUpload组件
核心类:
FileItemFactory FileItem的工厂
ServletFileUpload servlet 中的文件上传的核心类
FileItem 封装了上传的表单文件项的信息
总之 文件上传,处理起来比较麻烦
Struts的文件上传
文件上传 * 帮助我们晚场了文件上传的功能
<interceptor
name="fileUpload"
class="org.apache.structs2.interceptor.FileUploadInterceptor"/>
upload.xml
<struts>
<package name="upload_" extends="struts-default">
<!-- 注意: action 的名称不能用关键字"fileUpload" -->
<action name="fileUploadAction" class="cn.itcast.e_fileupload.FileUpload">
<!-- 限制运行上传的文件的类型 -->
<interceptor-ref name="defaultStack">
<!-- 限制运行的文件的扩展名 -->
<param name="fileUpload.allowedExtensions">txt,jpg,jar</param>
<!-- 限制运行的类型 【与上面同时使用,取交集】
<param name="fileUpload.allowedTypes">text/plain</param>
-->
</interceptor-ref>
<result name="success">/e/success.jsp</result>
<!-- 配置错误视图 -->
<result name="input">/e/error.jsp</result>
</action>
</package>
</struts>
upload.jsp
<body>
<form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="userName"><br/>
文件:<input type="file" name="file1"><br/>
<input type="submit" value="上传">
</form>
</body>
error.jsp
<body>
error.jsp<br/>
<!-- 查看struts框架在运行时期产生的所有错误信息 -->
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:fielderror></s:fielderror>
</body>
success.jsp
<body>
success.jsp
</body>
核心代码
FileUpload .class
public class FileUpload extends ActionSupport {
// 对应表单:<input type="file" name="file1">
private File file1;
// 文件名
private String file1FileName;
// 文件的类型(MIME)
private String file1ContentType;
public void setFile1(File file1) {
this.file1 = file1;
}
public void setFile1FileName(String file1FileName) {
this.file1FileName = file1FileName;
}
public void setFile1ContentType(String file1ContentType) {
this.file1ContentType = file1ContentType;
}
@Override
public String execute() throws Exception {
/******拿到上传的文件,进行处理******/
// 把文件上传到upload目录
// 获取上传的目录路径
String path = ServletActionContext.getServletContext().getRealPath("/upload");
// 创建目标文件对象
File destFile = new File(path,file1FileName);
// 把上传的文件,拷贝到目标文件中
FileUtils.copyFile(file1, destFile);
return SUCCESS;
}
}
文件上传处理细节
a.文件大小限制
structs默认支持的文件上传最大是2M,通过常量修改:
<!-- 4. 修改上传文件的最大大小为30M -->
<constant name="struts.multipart.maxSize" value="31457280"/>
b.限制上传文件的允许类型
需求:只允许txt/jpg后缀的文件
* :注入参数从而限制文件上传类型
<!-- 限制运行上传的文件的类型 -->
<interceptor-ref name="defaultStack">
<!-- 限制运行的文件的扩展名 -->
<param name="fileUpload.allowedExtensions">txt,jpg,jar</param>
<!-- 限制运行的类型 【与上面同时使用,取交集】
<param name="fileUpload.allowedTypes">text/plain</param>
-->
</interceptor-ref>
二、文件的下载
struts文件下载,2种方式:
方式1:通过response对象向浏览器写入字节流数据;设置下载的响应头
方式2:struts的方式
struts的文件下载:
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
首先注意在webroot目录下新建 upload 文件夹,把你要提供下载的文件放到该文件夹下,
upload.xml
<action name="down_*" class="cn.itcast.e_fileupload.DownAction" method="{1}">
<!-- 列表展示 -->
<result name="list">/e/list.jsp</result>
<!-- 下载操作 -->
<result name="download" type="stream">
<!-- 运行下载的文件的类型:指定为所有的二进制文件类型 -->
<param name="contentType">application/octet-stream</param>
<!-- 对应的是Action中属性: 返回流的属性【其实就是getAttrInputStream()】 -->
<param name="inputName">attrInputStream</param>
<!-- 下载头,包括:浏览器显示的文件名 -->
<param name="contentDisposition">attachment;filename=${downFileName}</param>
<!-- 缓冲区大小设置 -->
<param name="bufferSize">1024</param>
</result>
</action>
list.jsp
<body>
<table border="1" align="center">
<tr>
<td>编号</td>
<td>文件名</td>
<td>操作</td>
</tr>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="fileName" items="${fileNames}" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${fileName }</td>
<td>
<!-- 构建一个url -->
<c:url var="url" value="down_down">
<c:param name="fileName" value="${fileName}"></c:param>
</c:url>
<a href="${url }">下载</a>
</td>
</tr>
</c:forEach>
</table>
</body>
DownAction
/**
* 文件下载
* 1. 显示所有要下载文件的列表
* 2. 文件下载
*
*/
public class DownAction extends ActionSupport {
/*************1. 显示所有要下载文件的列表*********************/
public String list() throws Exception {
//得到upload目录路径
String path = ServletActionContext.getServletContext().getRealPath("/upload");
// 目录对象
File file = new File(path);
// 得到所有要下载的文件的文件名
String[] fileNames = file.list();
// 保存
ActionContext ac = ActionContext.getContext();
// 得到代表request的map (第二种方式)
Map<String,Object> request= (Map<String, Object>) ac.get("request");
request.put("fileNames", fileNames);
return "list";
}
/*************2. 文件下载*********************/
// 1. 获取要下载的文件的文件名
private String fileName;
public void setFileName(String fileName) {
// 处理传入的参数中问题(get提交)
try {
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// 把处理好的文件名,赋值
this.fileName = fileName;
}
//2. 下载提交的业务方法 (在struts.xml中配置返回stream)
public String down() throws Exception {
return "download";
}
// 3. 返回文件流的方法
public InputStream getAttrInputStream(){
return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);
}
// 4. 下载显示的文件名(浏览器显示的文件名)
public String getDownFileName() {
// 需要进行中文编码
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return fileName;
}
}
标签:struts2,上传,下载
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
关于SpringBoot静态资源路径管理问题
2022-12-04 03:51:29
![](https://img.aspxhome.com/file/2023/1/92551_0s.png)
C#实现一键清空控件值的示例代码
2021-11-12 12:10:15
![](https://img.aspxhome.com/file/2023/5/79105_0s.png)
Android异常处理最佳实践
2021-06-15 20:17:12
Android 读取资源文件实例详解
2022-08-28 13:31:17
Java线程池的优点及池化技术的应用
2022-07-01 08:12:23
![](https://img.aspxhome.com/file/2023/0/72290_0s.webp)
Java基于栈方式解决汉诺塔问题实例【递归与非递归算法】
2023-04-10 08:05:02
![](https://img.aspxhome.com/file/2023/3/64413_0s.jpg)
SpringBoot如何在普通类加载Spring容器
2023-10-06 03:56:27
Android CountDownTimer案例总结
2023-12-21 05:40:36
使用SpringBoot发送邮件的方法详解
2023-01-30 02:21:37
![](https://img.aspxhome.com/file/2023/7/73107_0s.webp)
Android使用分类型RecyclerView仿各大商城首页
2021-06-29 12:08:23
![](https://img.aspxhome.com/file/2023/6/137676_0s.jpg)
Java编程基本概念
2023-09-07 07:15:50
C#关于System.Collections空间详解
2022-04-12 16:04:06
Spring中RedisTemplate的基本使用浅析
2023-03-08 05:46:50
![](https://img.aspxhome.com/file/2023/4/92634_0s.png)
Android 调用设备已有的相机应用详情
2022-12-20 01:07:21
Mybatis延迟加载和缓存深入讲解
2022-06-02 15:50:43
![](https://img.aspxhome.com/file/2023/6/69686_0s.png)
深入了解C#设计模式之订阅发布模式
2021-08-14 05:31:39
C#字符串和Acsii码相互转换
2022-09-24 00:12:07
Android 如何获取手机总内存和可用内存等信息
2023-07-27 13:11:42
互斥量mutex的简单使用(实例讲解)
2023-09-20 21:36:50
超详细的Intellij IDEA 看源码必备技能
2021-10-27 09:03:16
![](https://img.aspxhome.com/file/2023/2/69312_0s.png)