Struts2实现文件上传时显示进度条功能
作者:surmounting 发布时间:2021-10-13 05:22:22
最近在做一个资源共享的项目中,采用了Struts2.1.8+Spring2.5.6+hibernate3.32的框架整合方式进行开发。在文件上传这块,因为需要实现文件上传时显示进度条的功能,所以尝试了一下。怕以后忘记,先贴出来分享下。
要在上传文件时能显示进度条,首先需要实时的获知web服务端接收了多少字节,以及文件总大小,这里我们在页面上使用AJAX技术每一秒向服务器发送一次请求来获得需要的实时上传信息。但是当我们使用struts2后怎么在服务端获得实时的上传大小呢?这里需要用到commons-fileupload中的progressListener接口,实现这个接口,然后再实现一个自己的解析器,并在解析器中添加自己实现的那个progressListener;然后再替换struts2自带的解析器(struts2自带的解析器类没有添加progressListener),然后就可以了。下面看看主要的代码(技术有限,如有不对之处,望不吝点解):
* :
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
public class ResourceProgressListener implements ProgressListener {
private HttpSession session;
public ResourceProgressListener(HttpServletRequest request) {
session = request.getSession();
ResourceFileUploadStatus newUploadStatus = new ResourceFileUploadStatus();
session.setAttribute("currentUploadStatus", newUploadStatus);
}
public void update(long readedBytes, long totalBytes, int currentItem) {
ResourceFileUploadStatus status = (ResourceFileUploadStatus) session.getAttribute("currentUploadStatus");
status.setReadedBytes(readedBytes);
status.setTotalBytes(totalBytes);
status.setCurrentItem(currentItem);
}
}
上传状态类:
public class ResourceFileUploadStatus {
private long readedBytes = 0L;
private long totalBytes = 0L;
private int currentItem = 0;
public long getReadedBytes() {
return readedBytes;
}
public void setReadedBytes(long bytes) {
readedBytes = bytes;
}
public long getTotalBytes() {
return totalBytes;
}
public void setTotalBytes(long bytes) {
totalBytes = bytes;
}
public int getCurrentItem() {
return currentItem;
}
public void setCurrentItem(int item) {
currentItem = item;
}
}
实现自己的解析器类:方法比较简单,找到struts2实现的解析器类,把代码拷贝过来然后添加上 * 即可。这个类代码较多就不整个文件拷了,主要是在parse方法里添加。Parse方法代码如下:红色标注部分即是需要自己添加的progressListener.
public void parse(HttpServletRequest servletRequest, String saveDir)
throws IOException {
System.out.println("执行自定义MultiPartRequest");
DiskFileItemFactory fac = new DiskFileItemFactory();
// Make sure that the data is written to file
fac.setSizeThreshold(0);
if (saveDir != null) {
fac.setRepository(new File(saveDir));
}
// Parse the request
try {
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setSizeMax(maxSize);
ResourceProgressListener progressListener = new ResourceProgressListener(servletRequest);//新建一个 *
upload.setProgressListener(progressListener);//添加自己的 *
List items = upload.parseRequest(createRequestContext(servletRequest));
for (Object item1 : items) {
FileItem item = (FileItem) item1;
if (LOG.isDebugEnabled()) LOG.debug("Found item " + item.getFieldName());
if (item.isFormField()) {
LOG.debug("Item is a normal form field");
List<String> values;
if (params.get(item.getFieldName()) != null) {
values = params.get(item.getFieldName());
} else {
values = new ArrayList<String>();
}
String charset = servletRequest.getCharacterEncoding();
if (charset != null) {
values.add(item.getString(charset));
} else {
values.add(item.getString());
}
params.put(item.getFieldName(), values);
} else {
LOG.debug("Item is a file upload");
// Skip file uploads that don't have a file name - meaning that no file was selected.
if (item.getName() == null || item.getName().trim().length() < 1) {
LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
continue;
}
List<FileItem> values;
if (files.get(item.getFieldName()) != null) {
values = files.get(item.getFieldName());
} else {
values = new ArrayList<FileItem>();
}
values.add(item);
files.put(item.getFieldName(), values);
}
}
} catch (FileUploadException e) {
LOG.warn("Unable to parse request", e);
errors.add(e.getMessage());
}
}
上面的类建立完成后,还需要做一项工作:在struts.xml中添加如下内容:
<bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" name="requestParser"
class="com.zeige.ResourceMultiPartRequest" scope="default" optional="true" />
<constant name="struts.multipart.handler" value="requestParser" />
下面就可以正常使用了,建立两个action,一个用来接收上传文件,以及对接收的文件作相应处理,处理完成后,在return SUCCESS之前去除session中currentUploadStatus属性,一个用来为页面读取实时上传进度服务,这个类中只要将session中的currentUploadStatus对象拿出来按照相应格式返回给客户端即可。


猜你喜欢
- 本文演示android中图片加载到内存首先设计界面:代码如下:<LinearLayout xmlns:android="ht
- Java执行cmd命令//当前绝对路径System.out.println(IoUtil.read(Runtime.getRuntime()
- 一. string的构造函数的形式:string str:生成空字符串string s(str):生成字符串为str的复制品string s
- 目录数据类型布尔类型字符串类型String拼接字符'+'转义字符运算符加减乘除模运算增量赋值运算符自增运算符和自建运算符赋值
- 目录前言if-thenif-then-elseswitch使用 Stringwhiledo-whileforbreakcontinueret
- 本文实例展示了DevExpress实现自定义TreeListNode的Tooltip的方法,具体方法如下所示:主要功能代码如下:/// &l
- package com.imoyo.expert;import java.util.ArrayList;import android.app
- 问答小剧场 以下会产生信息丢失的类型转换是( ) A.float a=10;
- 前言此文适合了解了es相关概念以及基础知识的同学阅读elasticsearch简介Elasticsearch是一个基于Lucene的搜索服务
- 最近公司在新版本上有一个需要,要在首页添加一个滑动效果,具体就是仿照X宝的商品详情页,拉到页面底部时有一个粘滞效果,如下图X东的商品详情页,
- /** * 日期工具类 * 默认使用 "yyyy-MM-dd HH:mm:ss" 格式化日期&nbs
- 测试是开发的一个非常重要的方面,可以在很大程度上决定一个应用程序的命运。良好的测试可以在早期捕获导致应用程序崩溃的问题,但较差的测试往往总是
- Vector实现了AbstractList抽象类和List接口,和ArrayList一样是基于Array存储的Vector 是线程安全的,在
- 提到java里的注解,和我们平时的注释还是有很大的区别,主要是作为java特性来使用的,跟我们常见的类是同一个使用的层面。关于java注解的
- 使用idea的file-》settings-》plugins安装maven helper插件失败,安装页面总是提示installed,在in
- 前言.NET中的委托是一个类,它定义了方法的类型,是一个方法容器。委托把方法当作参数,可以避免在程序中大量使用条件判断语句的情况。项目名为T
- Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。使用Reflections可以很轻松的获取以下
- 本文实例为大家分享了android实现手机截屏并保存截图功能的具体代码,供大家参考,具体内容如下一、准备一张图片拷贝screenshot_p
- 在使用spring框架中我们都知道,某个类如果使用了@Service、@Autowire 这种依赖注入的方式引用了其他对象,在另外一个类中,
- IISExpress 配置允许外部访问详细介绍1.找到IISExpress的配置文件,位于 <文档>/IISExpr