欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Struts2 文件上传进度条的实现实例代码

程序员文章站 2024-02-23 20:27:52
最近在写我们大三项目的一个视频文件上传的页面,实现后台对上传的进度进行监听,然后将监听的信息返回给前台页面。 前台的页面效果图: 前台进度条控件选择使用easyui...

最近在写我们大三项目的一个视频文件上传的页面,实现后台对上传的进度进行监听,然后将监听的信息返回给前台页面。

前台的页面效果图:

Struts2 文件上传进度条的实现实例代码

前台进度条控件选择使用easyui 的progressbar控件。

详细的使用说明参考官网文档:

所有需要引入jquery-1.11.1.min.js 以及jquery.easyui.min.js

一.前台的代码:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>

<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
 <head>
  <base href="<%=basepath%>" rel="external nofollow" >
  <title>my jsp 'uploadvideo.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">  
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="this is my page">
  <link rel="stylesheet" href="demo.css" rel="external nofollow" />
  <link rel="stylesheet" href="easyui.css" rel="external nofollow" />
  <link rel="stylesheet" href="icon.css" rel="external nofollow" />
  <script type="text/javascript" src="jquery.min.js" ></script>
  <script type="text/javascript" src="jquery.easyui.min.js" ></script>
  <link rel="stylesheet" href="videocss/upload.css" rel="external nofollow" />
  <script>
  $(function() {
    var pro=0;
    $("#save").click(function(){
      savedate();
      setinterval=setinterval(showuploadprogress, 100); 
    });
    function savedate(){
    var form = new formdata(document.getelementbyid("form"));
      $.ajax({
        type:"post",
        url:"uploadfile.action",
        data:form,
        async:false,
        cache:false,
        processdata:false,
        contenttype:false,
        success:function(result){
          var msg=result.msg;
          $(".msg").text(msg);
        },
        error:function(){
          alert("file异步提交失败");
        }
      });
    }
    
    function showuploadprogress(){
      $.ajax({
        type:"get",
        url:"uploadprogress.action",
        datatype:"json",
        async:false,
        cache:false,
        success:function(result){
          var progressinfo=result.progressinfo;
          pro=progressinfo.percent;
          if(pro==100){
            clearinterval(setinterval);
          }
          $('#progress').progressbar('setvalue', progressinfo.percent);
          $('progress-bar-status').find(".speed").text(progressinfo.velocity);
          $('progress-bar-status').find(".finished").text("已上传:"+progressinfo.length+"/"+progressinfo.totallength);
          $('progress-bar-status').find(".remain").text(progressinfo.timeleft);
        },
        error:function(result){
           alert("error1"); 
        }
      });
    }
    
    
    
  });
  </script>
 </head>
 
  <body>
    <div class="main_wrapper">
        <div class="head_wrapper">
          <div class="headinside">
            <ul>
              <li><a href="">主站</a></li>
              <li><a href="">视频栏</a></li>
              <li><a href="">资源区</a></li>
              <li><a href="">个人中心</a></li>
            </ul>
          </div>  
        </div><!--head_wrapper结束-->
        <div class="upload_box">
          <p id="error">
            <s:fielderror name="struts.messages.error.content.type.not.allowed"></s:fielderror>
            <s:actionerror/>
            <font color="red" class="msg">${msg }</font>
          </p>
           <div class="uploadinfo">
           <span class="title">
             当前上传:
             <span class="filename">文件名</span>
           </span>
           <div id="progress" class="easyui-progressbar" style="width:400px;"></div>
           <div class="progress-bar-status">
             <span class="speed" style="display: none;">当前上传的速度:80.23k/s</span>
             <span class="finished">已上传:10.86m/10.86m</span>
             <span class="remain" style="display:none">剩余时间:00秒</span>
           </div>
           <div class="videoinfo">
           <form method="post" enctype="multipart/form-data" id="form">
             <ul>
               <li>
                 <div>
                   <label for="video1">文件上传</label>
                    <input type="file" id="btn_file" name="video"/>
                 </div>
               </li>
               <li>
                 
                   <label for="name">标题</label>
                   <input type="text" name="name" id="name" title="标题" placeholder="给你的视频七个标题名吧"/>
                 
               </li>
               <li>
                 <div>
                   <label for="cate">分类</label>
                   <select class="cate" id="cate" name="cate">
                   <option value ="1">传统文学</option>
                   <option value ="2">民间手工艺</option>
                   <option value="3">节假日常</option>
                  </select>
                </div>
               </li>
               <li>
                 <div>
                   <label for="tag">标签</label>
                   <input type="text" name="tag" id="tag" placeholder="请给您的视频添加相应的标签"/>
                 </div>
               </li>
               <li>
                 <div>
                   <label for="desc" id="label_desc">描述</label>
                   <textarea name="videodesc" id="desc" placeholder="请添加相应的视频描述" >
                   </textarea>
                 </div>
               </li>
               <input id="save" type="button" value="保存"/>
               <!-- <button id="save">保存</button> -->
             </ul>
           </form>
           </div>
        </div>
        </div>
    </div>
    <div style="width: 100%;">
         <div class="footer" style="width: 100%;">
           <div class="inner">
             <p class="a_menu">
               <a target="_blank" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >关于我们</a>
               <i class="line">|</i>
               <a target="_blank" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >联系合作</a>
               <i class="line">|</i>
               <a target="_blank" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >帮助中心</a>
               <i class="line">|</i>
               <a target="_blank" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >合伙人计划</a>
               <i class="line">|</i>
               <a target="_blank" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >版权声明</a>
             </p>
             <p class="center">
               <span>江西师范大学瑶湖校区</span>
               <span>java工作室</span>
               <br>
               copyright&copy 大白 
             </p>
           </div>
         </div>
       </div>
   </body>
</html>

二.点击上传后,如何获得文上传的进度信息。

  1.自定义一个uploadlistener类实现org.apache.commons.fileupload中的progresslistener接口,从而获得当前上传的文件的已读取的数据长度,文件总长度,正在保存第几个文件;

  2.重写一个mymultipartrequest类,覆盖org.apache.struts2.dispatcher.multipart.jakartamultipartrequest,改写parserequest方法,在其中为上传添加监听器;

  3.定义一个uploadstatus bean类存放上传的状态信息,并将获得上传进度信息的uploadstatus对象存在在session域中;

  4.编写uploadlistenaction,获取session域中的uploadstatus对象,进行相应的数据处理,然后将需要的数据放入map中以json的形式返回给jsp;

  5.编写uploadfile.action,实现文件的上传存储;

三.相对应的代码。

package video.action;

import org.apache.commons.fileupload.progresslistener;

public class uploadlistener implements progresslistener {
  private uploadstatus status;
  
  public uploadlistener(uploadstatus status) {
    this.status = status;
  }

   public void update(long bytesread, long contentlength, int items) {
      // 上传组件会调用该方法
      status.setbytesread(bytesread); // 已读取的数据长度
      status.setcontentlength(contentlength); // 文件总长度
      status.setitems(items); // 正在保存第几个文件
      
   }
  
}

对于步骤2中mymultipartrequest修改后的方法代码。

protected list<fileitem> parserequest(httpservletrequest servletrequest, string savedir) throws fileuploadexception {
     uploadstatus status = new uploadstatus(); // 上传状态
     uploadlistener listner = new uploadlistener(status); // 监听器
     servletrequest.getsession().setattribute("uploadstatus", status);//将上传的进度状态存放进session;
    
     diskfileitemfactory fac = creatediskfileitemfactory(savedir);
     servletfileupload upload = createservletfileupload(fac);
     
     upload.setprogresslistener(listner);// 添加监听器
    return upload.parserequest(createrequestcontext(servletrequest));
  }
package video.action;

public class uploadstatus {
  private long bytesread; // 已经上传的字节数,单位:字节
  private long contentlength; // 所有文件的总长度,单位:字节
  private int items; // 正在上传第几个文件
  private long starttime = system.currenttimemillis(); // 开始上传的时间,用于计算上传速度等
  
  public long getbytesread() {
    return bytesread;
  }

  public void setbytesread(long bytesread) {
    this.bytesread = bytesread;
  }

  public long getcontentlength() {
    return contentlength;
  }

  public void setcontentlength(long contentlength) {
    this.contentlength = contentlength;
  }

  public int getitems() {
    return items;
  }

  public void setitems(int items) {
    this.items = items;
  }

  public long getstarttime() {
    return starttime;
  }

  public void setstarttime(long starttime) {
    this.starttime = starttime;
  }
}

package video.action;

import java.util.hashmap;
import java.util.map;

import org.apache.struts2.interceptor.sessionaware;

import com.opensymphony.xwork2.actionsupport;

public class uploadlistenaction extends actionsupport implements sessionaware{
  private uploadstatus status;
  map<string,object> session;
  map<string,string> progressinfo=new hashmap<>();
  @override
  public string execute() throws exception {
    // todo auto-generated method stub
    status=(uploadstatus)session.get("uploadstatus");
    if(status!=null){
      long starttime = status.getstarttime(); //上传开始时间
      long currenttime = system.currenttimemillis(); //现在时间
      long time = (currenttime - starttime)/ 1000 + 1; //已传输的时间 单位:s
      //传输速度单位:byte/s
      double velocity = ((double)status.getbytesread()/1000) / (double)time;
     //估计总时间
      double totaltime = status.getcontentlength()/velocity;
     //估计剩余时间
      double timeleft = totaltime - time;
      //已经完成的百分比
      int percent = (int)(100 * (double)status.getbytesread() / (double)status.getcontentlength());
      //已经完成数单位:m
      double length = ((double) status.getbytesread())/1024/1024;
      //总长度 单位:m
      double totallength = ((double) status.getcontentlength())/1024/1024;
      progressinfo.put("percent", string.valueof(percent));
      progressinfo.put("velocity", string.valueof(velocity));
      progressinfo.put("totaltime", string.valueof(totaltime));
      progressinfo.put("timeleft", string.valueof(timeleft));
      progressinfo.put("length", string.valueof(length));
      progressinfo.put("totallength", string.valueof(totallength));
    }
    
    return super.execute();
  }
  @override
  public void setsession(map<string, object> session) {
    // todo auto-generated method stub
    this.session=session;
  }
  public map<string, string> getprogressinfo() {
    return progressinfo;
  }
  
  /*public uploadstatus getstatus() {
    return status;
  }*/
  
}

package video.action;

import java.io.file;
import java.text.simpledateformat;
import java.util.date;
import java.util.map;

import javax.servlet.servletcontext;

import org.apache.commons.io.fileutils;
import org.apache.struts2.servletactioncontext;
import org.apache.struts2.interceptor.sessionaware;

import video.dao.uploaddao;
import video.daoimpl.uploaddaoimpl;
import videomodel.videoinfo;
import cn.history.pojo.user;

import com.opensymphony.xwork2.actioncontext;
import com.opensymphony.xwork2.actionsupport;

public class uploadfile extends actionsupport{
  private static final long serialversionuid = 4182168930616232826l;
  private string name;  //标题名
  private file video;    
  private string videofilename;
  private string videocontenttype;
  private string videodesc;  //描述
  private int cate;      //类型
  private string tag;      //标签
  /*private videoinfo videoinfo=new videoinfo();*/
  private string msg;

  private uploaddao uploaddao=new uploaddaoimpl();
  public string upload() throws exception{
    //完成上传
    servletcontext sc=servletactioncontext.getservletcontext();
    string directory=sc.getrealpath("/video");//得到存放文件的真是目录
    //根据视频的不同类型,存放在不同的目录下
    if(cate==1){  //如果是传统文学
      directory=directory+"/guoxue";
    }else if(cate==2){
      directory=directory+"/minjian";
    }else{
      directory=directory+"/jiari";
    }
    simpledateformat sdf=new simpledateformat("yyyymmddhhmmsss");//格式化时间输出
    string rname=null;
    if(name!=null&&!name.equals("")){
      rname=name+"_"+sdf.format(new date())+".mp4";
    }else{
      rname=videofilename;
    }
    system.out.println(rname);
    //构建目标文件
    file target=new file(directory,rname);
    fileutils.copyfile(video, target);
    system.out.println(rname+"\n"+videofilename+"\n"+videodesc+"\n"+videocontenttype);
    //将成功上传的视频基本信息保存至数据库m
    string filepath=target.getpath();
    filepath=filepath.substring(filepath.indexof("video")).replace("\\", "/");
    system.out.println(filepath);
    videoinfo videoinfo=new videoinfo();
    videoinfo.setvideoname(rname);
    videoinfo.setvideodesc(videodesc);
    videoinfo.setvideourl(filepath);
    videoinfo.setcate(cate);
    videoinfo.settag(tag);
    //actioncontext.getcontext().getsession().get("name");
    if(actioncontext.getcontext().getsession().get("user")!=null){
      user user=(user) actioncontext.getcontext().getsession().get("user");
      videoinfo.setauthorid(user.getuser_id());
    }else{
      //设置为管理员的id,默认是管理员上传的
      videoinfo.setauthorid(1);
    }
    int tag=uploaddao.savevideo(videoinfo);
    if(tag==0){
      msg="上传失败(存储数据库过程出错)";
      return input;
    }else{
      msg="视频上传成功";
    }
    return success;
  }
  
/*  public videoinfo getvideoinfo() {
    return videoinfo;
  }

  public void setvideoinfo(videoinfo videoinfo) {
    this.videoinfo = videoinfo;
  }*/

  /*public string getname() {
    return name;
  }*/

  public void setname(string name) {
    this.name = name;
  }

//  public file getvideo() {
//    return video;
//  }

  public void setvideo(file video) {
    system.out.println(video);
    this.video = video;
  }
  
//  public string getvideodesc() {
//    return videodesc;
//  }
  public void setvideodesc(string videodesc) {
    this.videodesc = videodesc;
  }
  
  /*public int getcate() {
    return cate;
  }*/

  public void setcate(int cate) {
    this.cate = cate;
  }
  
  /*public string gettag() {
    return tag;
  }*/

  public void settag(string tag) {
    this.tag = tag;
  }

//  public string getvideofilename() {
//    return videofilename;
//  }

  public void setvideofilename(string videofilename) {
    this.videofilename = videofilename;
  }

  /*public string getvideocontenttype() {
    return videocontenttype;
  }*/

  public void setvideocontenttype(string videocontenttype) {
    this.videocontenttype = videocontenttype;
  }
  public string getmsg() {
    return msg;
  }
  public void setmsg(string msg) {
    this.msg = msg;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。