springboot上传文件显示上传进度

news/2024/7/24 6:47:45 标签: springboot, 进度条

springboot_0">springboot上传文件显示上传进度

  1. 创建maven依赖
		<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
  1. 新建实体类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class ProgressEntity {


    /**
     * 读取的文件的比特数
     */
    private long bytesRead = 0L;

    /**
     * 文件的总大小
      */
    private long contentLength = 0L;

    /**
     * 目前正在读取第几个文件
     */
    private int items;

    /**
     *  开始上传时间,用于计算上传速率
     */
    private long startTime = System.currentTimeMillis();

}
  1. 新建监听器
/**
 *
 * @author Administrator
 *
 * 要获得上传文件的实时详细信息,必须继承org.apache.commons.fileupload.ProgressListener类,
 * 获得信息的时候将进度条对象Progress放在该监听器的session对象中
 */
@Component
public class FileUploadProgressListener implements ProgressListener {

    private HttpSession session;

    public void setSession(HttpSession session){
        this.session=session;
        //保存上传状态
        ProgressEntity progressEntity = new ProgressEntity();
        session.setAttribute("progressEntity", progressEntity);
    }

    @Override
    public void update(long bytesRead, long contentLength, int items) {
        ProgressEntity progressEntity = (ProgressEntity) session.getAttribute("progressEntity");
        //已读取数据长度
        progressEntity.setBytesRead(bytesRead);
        //文件总长度
        progressEntity.setContentLength(contentLength);
        //正在保存第几个文件
        progressEntity.setItems(items);
    }
}

  1. 新建文件解析器
/**
 * @author Administrator
 *
 * SpringMVC默认有一个文件解析器CommonsMultipartResolver用来解析上传的文件,我们需要重写该类,
 * 自己重写的监听器放到org.apache.commons.fileupload.FileUpload中,还需要将session放到自定义的监听器中
 */

public class CustomMultipartResolver extends CommonsMultipartResolver {

    /**
     * 注入第二步写的FileUploadProgressListener
     * 此处一定要检查是否注入成功了,不成功的话会报错
     */
    @Autowired
    private FileUploadProgressListener progressListener;

    public void setProgressListener(FileUploadProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    @Override
    public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        progressListener.setSession(request.getSession());
        fileUpload.setProgressListener(progressListener);
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Could not parse multipart servlet request", ex);
        }
    }

}
  1. 指定自定义解析器
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    /**
     * 指定自定义解析器
     * 将 multipartResolver 指向我们刚刚创建好的继承 CustomMultipartResolver 类的 自定义文件上传处理类
     *
     * @return
     */
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        return new CustomMultipartResolver();
    }
}
  1. 控制器调用方法
 /**
     * 获取上传进度
     *
     * @return
     */
    @GetMapping(value = "/uploadStatus")
    @ApiOperation("获取上传进度")
    public Object uploadStatus() {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        HttpSession session = request.getSession();
        ProgressEntity percent = (ProgressEntity) session.getAttribute("progressEntity");
       // System.out.println("^^^^"+percent.toString());
      //当前时间
        long nowTime = System.currentTimeMillis();
        //已传输的时间
        long time = (nowTime - percent.getStartTime())/1000+1;
        //传输速度 ;单位:byte/秒
        double velocity =((double) percent.getBytesRead())/(double)time;
        //估计总时间
        double totalTime = percent.getContentLength()/velocity;
        //估计剩余时间
        double timeLeft = totalTime - time;
        //已经完成的百分比
        int percent1 = (int)(100 * (double) percent.getBytesRead() / (double) percent.getContentLength());
        //已经完成数单位:m
        double length = ((double) percent.getBytesRead())/1024/1024;
        //总长度  M
        double totalLength = (double) percent.getContentLength()/1024/1024;
        StringBuffer sb = new StringBuffer();
        //拼接上传信息传递到jsp中
        sb.append(percent+":"+length+":"+totalLength+":"+velocity+":"+time+":"+totalTime+":"+timeLeft+":"+percent.getItems());
        System.out.println("百分比====>"+percent1);
        System.out.println("已传输时间====>"+time+"------剩余时间--->"+timeLeft+"======已经完成===="+length);
        return null;
    }

原文链接:https://blog.csdn.net/FurtherSkyQ/article/details/98200965


http://www.niftyadmin.cn/n/1302260.html

相关文章

CAS学习(二)不使用Cookie实现前后端分离情况下的CAS单点登录

上一篇已经介绍了将CAS6.2编译为服务&#xff0c;放在Tomcat中运行 地址&#xff1a;https://blog.csdn.net/u011943534/article/details/118437235 按照CAS官方的流程&#xff0c;需要借用Cookie实现TGC的传递&#xff0c;这里实验不使用Cookie实现了单点登录 第一个服务的单点…

支付宝报错: invalid-signature 错误原因: 验签出错,建议检查签名字符串或签名私钥与应用公钥是否匹配,网关生成的验签字符串为:xxx

错误代码 invalid-signature 错误原因: 验签出错&#xff0c;建议检查签名字符串或签名私钥与应用公钥是否匹配&#xff0c;网关生成的验签字符串为&#xff1a;xxx https://blog.csdn.net/weixin_44021888/article/details/106948733 该篇博客获取支付页&#xff1a; <fo…

@EventListener VS @TransactionalEventListener

EventListenerTransactionalEventListenerTransactionPhase

java实现将线程绑定到某个CPU核上(线程亲和性)

如果需要开发低延迟的网络应用&#xff0c;那应该对线程亲和性&#xff08;Thread affinity&#xff09;有所了解。线程亲和性能够强制使你的应用线程运行在特定的一个或多个cpu上。通过这种方式&#xff0c;可以消除操作系统进行调度造成的线程的频繁的上下文切换。 实现方式…

Nginx学习(十四) nginx开启HTTP2协议

当前只有https才支持http2协议&#xff0c;nginx需要开启支持http2的模块with-http_v2_module 安装过程参考上一篇:https://blog.csdn.net/u011943534/article/details/118384917 安装过程中&#xff0c;添加http2即可 ./configure --prefix/usr/local/nginx --with-http_ssl…

解决IDEA中gradle不编译mybatis的xml文件的问题

gradle默认只会把resource文件夹当成资源文件&#xff0c;如果mapper文件放在java目录&#xff0c;则编译后不会在out或build下的rensource中生成这写mapper文件。 需要在build.gradle文件中添加配置&#xff0c;将src/main/java下的文件也当作资源文件即可 sourceSets.main.r…

MySQL 实现多张无关联表查询数据并分页

MySQL 实现多张无关联表查询数据并分页 1、功能需求 在三张没有主外键关联的表中取出自己想要的数据&#xff0c;并且分页。 2、数据库表结构 水果表&#xff1a; 坚果表&#xff1a; 饮料表&#xff1a; 主要用UNION AL UNION ALL 操作符用于合并两个或多个 SELECT 语…

springboot2 配置404、403、500等错误页面自动跳转

springboot2 配置404、403、500等错误页面自动跳转 创建配置类ErrorPageConfig import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.ErrorPageRegistrar; import org.springframework.boot.web.server.ErrorPageRegistry; i…