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

ajax 异步上传带进度条视频并提取缩略图

程序员文章站 2022-06-03 15:08:32
最近在做一个集富媒体功能于一身的项目。需要上传视频。这里我希望做成异步上传,并且有进度条,响应有状态码,视频连接,缩略图。 服务端响应 { "thum...

最近在做一个集富媒体功能于一身的项目。需要上传视频。这里我希望做成异步上传,并且有进度条,响应有状态码,视频连接,缩略图。

服务端响应

 {
   "thumbnail": "/slsxpt//upload/thumbnail/fdceefc.jpg",
   "success": true,
   "link": "/slsxpt//upload/video/fdceefc.mp"
 }

并且希望我的input file控件不要被form标签包裹。原因是form中不能嵌套form,另外form标签在浏览器了还是有一点点默认样式的,搞不好又要写css。

以前用ajaxfileupload做过文件异步上传。不过这个东西好久未更新,代码还有bug,虽然最后勉强成功用上了,但总觉不好。而且ajaxfileupload没有直接添加xhr2的progress事件响应,比较麻烦。

上网找了一下,发现方法都是很多。

比如在文件上传后,将上传进度放到session中,轮询服务器session。但我总觉的这个方法有问题,我认为这种方法看到的进度,应该是我的服务端应用程序代码(我的也就是action)从服务器的临时目录复制文件的进度,因为所有请求都应该先提交给服务器软件,也就是tomcat,tomcat对请求进行封装session,request等对象,并且文件实际上也应该是它来接收的。也就是说在我的action代码执行之前,文件实际上已经上传完毕了。

后来找到个比较好的方法使用 jquery.form.js插件的ajaxsubmit方法。这个方法以表单来提交,也就是 $.fn.ajaxsubmit.:$(form selector).ajaxsubmit({}),这个api的好处是它已经对xhr2的progress时间进行了处理,可以在调用时传递一个uploadprogress的function,在function里就能够拿到进度。而且如果不想input file被form包裹也没关系,在代码里createelement应该可以。不过这个方法我因为犯了个小错误最后没有成功,可惜了。

ajaxsubmit源码

最后,还是使用了$.ajax 方法来做。$.ajax 不需要关联form,有点像个静态方法哦。唯一的遗憾就是$.ajax options里没有对progress的响应。不过它有一个参数为 xhr ,也就是你可以定制xhr,那么久可以通过xhr添加progress的事件处理程序。再结合看一看ajaxsubmit方法里对progress事件的处理,顿时豁然开朗

ajax 异步上传带进度条视频并提取缩略图

那么我也可以在$.ajax 方法中添加progress事件处理函数了。为了把对dom的操作从上传业务中抽取出来,我决定以插件的形式写。下面是插件的代码

 ;(function ($) {
   var defaults = {
       uploadprogress    :  null,
       beforesend      :  null,
       success        :  null,
     },
     setting = {
     };
   var upload = function($this){
     $this.parent().on('change',$this,function(event){
       //var $this = $(event.target),
       var  formdata = new formdata(),
         target = event.target || event.srcelement;
       //$.each(target.files, function(key, value)
       //{
       //  console.log(key);
       //  formdata.append(key, value);
       //});
       formdata.append('file',target.files[]);
       settings.filetype && formdata.append('filetype',settings.filetype);
       $.ajax({
         url        :  $this.data('url'),
         type      :  "post",
         data      :  formdata,
         datatype    :  'json',
         processdata    :  false,
         contenttype    :  false,
         cache      :  false,
         beforesend    :  function(){
           //console.log('start');
           if(settings.beforesend){
             settings.beforesend();
           }
         },
         xhr        :   function() {
           var xhr = $.ajaxsettings.xhr();
           if(xhr.upload){
             xhr.upload.addeventlistener('progress',function(event){
               var total = event.total,
                 position = event.loaded || event.position,
                 percent = ;
               if(event.lengthcomputable){
                 percent = math.ceil(position / total * );
               }
               if(settings.uploadprogress){
                 settings.uploadprogress(event, position, total, percent);
               }
             }, false);
           }
           return xhr;
         },
         success      :  function(data,status,jxhr){
           if(settings.success){
             settings.success(data);
           }
         },
         error      :  function(jxhr,status,error){
           if(settings.error){
             settings.error(jxhr,status,error);
           }
         }
       });
     });
   };
   $.fn.uploadfile = function (options) {
     settings = $.extend({}, defaults, options);
     // 文件上传
     return this.each(function(){
       upload($(this));
     });
   }
 })($ || jquery);

下面就可以在我的jsp页面里面使用这个api了。

<div class="col-sm-">
   <input type="text" name="resource_url" id="resource_url" hidden="hidden"/>
   <div class="progress" style='display: none;'>
     <div class="progress-bar progress-bar-success uploadvideoprogress" role="progressbar"
        aria-valuenow="" aria-valuemin="" aria-valuemax="" style="width: %">
     </div>
   </div>
   <input type="file" class="form-control file inline btn btn-primary uploadinput uploadvideo"
      accept="video/mp"
      data-url="${baseurl}/upload-video.action"
      data-label="<i class='glyphicon glyphicon-circle-arrow-up'></i>  选择文件" />
   <script>
     (function($){
       $(document).ready(function(){
         var $progress  = $('.uploadvideoprogress'),
             start = false;
         $('input.uploadinput.uploadvideo').uploadfile({
           beforesend   : function(){
             $progress.parent().show();
           },
           uploadprogress : function(event, position, total, percent){
             $progress.attr('aria-valuenow',percent);
             $progress.width(percent+'%');
             if(percent >= ){
               $progress.parent().hide();
               $progress.attr('aria-valuenow',);
               $progress.width(+'%');
             }
           },
           success     : function(data){
             if(data.success){
               settimeout(function(){
                 $('#thumbnail').attr('src',data.thumbnail);
               },);
             }
           }
         });
       });
     })(jquery);
   </script>
 </div>

这里在响应succes的时候设置超时800毫秒之后获取图片,因为提取缩量图是另一个进程在做可能响应完成的时候缩略图还没提取完成

看下效果

ajax 异步上传带进度条视频并提取缩略图

提取缩量图

下面部分就是服务端处理上传,并且对视频提取缩量图下面是action的处理代码

package org.lyh.app.actions;
 import org.apache.commons.io.fileutils;
 import org.apache.struts.servletactioncontext;
 import org.lyh.app.base.baseaction;
 import org.lyh.library.sitehelpers;
 import org.lyh.library.videoutils;
 import java.io.file;
 import java.io.ioexception;
 import java.security.keystore;
 import java.util.hashmap;
 import java.util.map;
 /**
 * created by admin on //.
 */
 public class uploadaction extends baseaction{
   private string savebasepath;
   private string imagepath;
   private string videopath;
   private string audiopath;
   private string thumbnailpath;
   private file file;
   private string filefilename;
   private string filecontenttype;
   // 省略setter getter方法
   public string video() {
     map<string, object> datajson = new hashmap<string, object>();
     system.out.println(file);
     system.out.println(filefilename);
     system.out.println(filecontenttype);
     string fileextend = filefilename.substring(filefilename.lastindexof("."));
     string newfilename = sitehelpers.md(filefilename + file.gettotalspace());
     string typedir = "normal";
     string thumbnailname = null,thumbnailfile = null;
     boolean needthumb = false,extractok = false;
     if (filecontenttype.contains("video")) {
       typedir = videopath;
       // 提取缩量图
       needthumb = true;
       thumbnailname = newfilename + ".jpg";
       thumbnailfile
           = app.getrealpath(savebasepath + thumbnailpath) + "/" + thumbnailname;
     }
     string realpath = app.getrealpath(savebasepath + typedir);
     file savefile = new file(realpath, newfilename + fileextend);
     // 存在同名文件,跳过
     if (!savefile.exists()) {
       if (!savefile.getparentfile().exists()) {
         savefile.getparentfile().mkdirs();
       }
       try {
         fileutils.copyfile(file, savefile);
         if(needthumb){
           extractok = videoutils.extractthumbnail(savefile, thumbnailfile);
           system.out.println("提取缩略图成功:"+extractok);
         }
         datajson.put("success", true);
       } catch (ioexception e) {
         system.out.println(e.getmessage());
         datajson.put("success", false);
       }
     }else{
       datajson.put("success", true);
     }
     if((boolean)datajson.get("success")){
       datajson.put("link",
           app.getcontextpath() + "/" + savebasepath + typedir + "/" + newfilename + fileextend);
       if(needthumb){
         datajson.put("thumbnail",
             app.getcontextpath() + "/" + savebasepath + thumbnailpath + "/" + thumbnailname);
       }
     }
     this.responcejson(datajson);
     return none;
   }
 }

action配置

 <action name="upload-*" class="uploadaction" method="{}">
     <param name="savebasepath">/upload</param>
     <param name="imagepath">/images</param>
     <param name="videopath">/video</param>
     <param name="audiopath">/audio</param>
     <param name="thumbnailpath">/thumbnail</param>
 </action>

这里个人认为,如果文件的名称跟大小完全一样的话,它们是一个文件的概率就非常大了,所以我这里取文件名跟文件大小做md5运算,应该可以稍微避免下重复上传相同文件了。

转码的时候用到ffmpeg。需要的可以去这里下载。

package org.lyh.library;
 import java.io.file;
 import java.io.ioexception;
 import java.io.inputstream;
 import java.util.arraylist;
 import java.util.list;
 /**
 * created by admin on //.
 */
 public class videoutils {
   public static final string ffmpeg_executor = "c:/software/ffmpeg.exe";
   public static final int thumbnail_width = ;
   public static final int thumbnail_height = ;
   public static boolean extractthumbnail(file inputfile,string thumbnailoutput){
     list<string> command = new arraylist<string>();
     file ffmpegexe = new file(ffmpeg_executor);
     if(!ffmpegexe.exists()){
       system.out.println("转码工具不存在");
       return false;
     }
     system.out.println(ffmpegexe.getabsolutepath());
     system.out.println(inputfile.getabsolutepath());
     command.add(ffmpegexe.getabsolutepath());
     command.add("-i");
     command.add(inputfile.getabsolutepath());
     command.add("-y");
     command.add("-f");
     command.add("image");
     command.add("-ss");
     command.add("");
     command.add("-t");
     command.add(".");
     command.add("-s");
     command.add(thumbnail_width+"*"+thumbnail_height);
     command.add(thumbnailoutput);
     processbuilder builder = new processbuilder();
     builder.command(command);
     builder.redirecterrorstream(true);
     try {
       long starttime = system.currenttimemillis();
       process process = builder.start();
       system.out.println("启动耗时"+(system.currenttimemillis()-starttime));
       return true;
     } catch (ioexception e) {
       e.printstacktrace();
       return false;
     }
   }
 }

另外这里由java启动了另外一个进程,在我看来他们应该是互不相干的,java启动了ffmpeg.exe之后,应该回来继续执行下面的代码,所以并不需要单独起一个线程去提取缩量图。测试看也发现耗时不多。每次长传耗时也区别不大,下面是两次上传同一个文件耗时

第一次

ajax 异步上传带进度条视频并提取缩略图

第二次

ajax 异步上传带进度条视频并提取缩略图

ajax 异步上传带进度条视频并提取缩略图

就用户体验来说没有很大的区别。

另外这里上传较大文件需要对tomcat和struct做点配置

修改tomcat下conf目录下的server.xml文件,为connector节点添加属性 maxpostsize="0"表示不显示上传大小

另外修改 struts.xml添加配置,这里的value单位为字节,这里大概300多mb