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

基于jquery ajax的多文件上传进度条过程解析

程序员文章站 2022-08-02 21:38:30
这篇文章主要介绍了基于jquery ajax的多文件上传进度条过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...

这篇文章主要介绍了基于jquery ajax的多文件上传进度条过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

效果图

基于jquery ajax的多文件上传进度条过程解析

前端代码,基于jquery

<!doctype html>
<html>
 <head>
  <title>主页</title>
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <style type="text/css">
      *{
        padding: 0;
        margin: 0;
      }
      table{
        width: 600px;
        text-align: center;
      }
  </style>
 </head>
 <body>
 
    <input type="file" id="imgsend" name="file" value="发送图片" multiple="multiple" />
      <table border="1" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <td>名称</td>
            <td>大小</td>
            <td>进度</td>
            <td>结果</td>
          </tr>
        </thead>
        <tbody>
          <!-- <tr>
              <td>xxx</td>
              <td>100</td>
              <td class="per">100%</td>
              <td class="result">成功</td>
           </tr>-->
        </tbody>
      </table>
 </body>
 <script type="text/javascript" src="/javascripts/jquery.js"> </script>
  
 <script type="text/javascript">
   
 ;(function($){
   $.fn.extend({
        uploadfile:function(option){
          var that = this;
          var defau = {
            type:"post",
            cache:false,
            url:"",
            data:{},
            processdata:false,
            contenttype:false,
            success:function(){},
            error:function(){},
            progress:function(){},
            sendbefore:function(){},
            filter:[], //可以接受的文件后缀
            upname:true //是否对文件名称转化大写比对
             
          }
          option = $.extend(true, defau, option);
           
         var  filep = that.attr("name") || "file"; //传给后端得 file对应字段
          console.log(filep)
          var files = that[0].files;
           
          option.sendbefore(files); //发送之前
           
          for(var i = 0,len = files.length; i < len; i++ ){
             var fs = files[i];
             var fnamearr = fs.name.split('.');
             var fnmae = fnamearr.pop();
             var str = '';
             if(option.upname){
                fnmae = fnmae.touppercase();
             }else{
                fnmae = fnmae.tolowercase();
             }
             if(option.filter.length > 0 && option.filter.indexof(fnmae) !== -1){
                option.error("文件后缀不符",i);  
                continue;
             }
             fileupload(files[i],i);
             
          }
           
          //开始文件上传
          function fileupload(file,index){
             var fd = new formdata();
             fd.append(filep,file);
             
             //追加其他参数
             for(var i in option.data){
                fd.append(i,option.data[i]);
             }
             
             $.ajax({
              url: option.url,
              type: option.type,
             data: fd,
             cache: option.cache,
             processdata: option.processdata,
             contenttype: option.contenttype,
              success:function(data){
                option.success(data,index);
                 
              },
              error:function(error){
                console.log(error);
                option.error(error,index);
              },
              xhr: function(){
                var xhr = $.ajaxsettings.xhr();
                if(onprogress && xhr.upload) {
                 xhr.upload.addeventlistener("progress" , onprogress, false);
                 return xhr;
                }
            }
             });
             
            function onprogress(evt){
              var loaded = evt.loaded;   //已经上传大小情况
             var tot = evt.total;   //附件总大小
             var per = math.floor(100*loaded/tot); //已经上传的百分比
              file.loaded = loaded;
              file.total = tot;
              file.percent = per + '%';
              file.index = index;
              option.progress(file);
            }
          }
          return that;
        }
   });
   
 })($,window);
 
  //发送图片
   
  var $table = $("table tbody");
   
  $("#imgsend").on('change',function(){
    var that = this;
     
     $(that).uploadfile({
      url:"/api/file",
      data:{},
      filter:[], //后缀文件筛选
      sendbefore:function(files){
         //开始之前
         console.log(files);
         var str = '';
         for(var i = 0; i < files.length; i++){
          var item = files[i];
          str += '<tr>'+
                '<td>'+ item.name +'</td>'+
                '<td>'+ formatsize (item.size) +'</td>'+
                '<td class="per">0</td>'+
                '<td class="result"></td>'+
              '</tr>';
         }
          
         $table.html(str);
          
      },
      success:function(data,index){
         //某个文件传完
        var $tr = $table.find('tr').eq(index);
        $tr.find('.result').html("成功");
      },
      error:function(err,index){
        //某个文件报错
        $tr.find('.result').html("失败");
      },
      progress:function(file){
        //某个文件的上传进度
         
        // file.loaded 已经上传的
        // flie.total 总量
        // file.percent 百分比
        // file.index  第多少个文件
        var $tr = $table.find('tr').eq(file.index);
        $tr.find('.per').html(file.percent);
        console.log(file.name + ":第" + file.index + '个:' + file.percent);
      }
      });
  });      
  //文件大小格式化
function formatsize (filesize) { 
  var arrunit = ["b", "k", "m", "g", "t", "p"], 
    basestep = 1024, 
    unitcount = arrunit.length, 
    unitindex = 0;          
  while(filesize >= basestep && unitindex < unitcount - 1){ 
    unitindex++; 
    filesize /= basestep; 
  } 
  filesize = filesize.tofixed(2); 
  return filesize + " " + arrunit[unitindex]; 
} 
 </script>
</html>

后端代码,nodejs+express

const multiparty = require('multiparty');
  var fs =require("fs");
 router.post('/api/file', function(req, res, next) {
  //生成multiparty对象,并配置上传目标路径
  const form = new multiparty.form()
  // //设置编辑
  form.encoding = 'utf-8'
  // //设置文件存储路径
  form.uploaddir = "./public/static/files/"
  // //设置单文件大小限制
  //form.maxfilessize = 2 * 1024 * 1024
  // form.maxfields = 1000; 设置所以文件的大小总和
  // 上传完成后处理
  form.parse(req, (err, fields, files) => {
   if (err) {
    console.log("parse:",err);
    res.json({"success":"error"});
   } else {
    const inputfile = files.file[0];
    const uploadedpath = inputfile.path
    const imgtype = inputfile.originalfilename;
    const inpath = `./public/static/files/${imgtype}`; //重命名的路径
    // 判断是否存在./dist/static/files文件
    fs.stat('./public/static/files', (err, stats) => {
     if (json.stringify(stats) === undefined) {
      fs.mkdirsync('./public/static', 0777)
      fs.mkdirsync('./public/static/files', 0777)
     }
     storefiles(uploadedpath, fields, inpath)
    });
   }
  });
   
  function storefiles(uploadedpath, fields, inpath) {
   //重命名为真实文件名
   fs.rename(uploadedpath, inpath, (err) => {
    if (err) {
      console.log("rename:",err);
      res.json({"success":"error"});
    } else {
          res.json({"success":"hahha"});
    }
   });
  }
});

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