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


Posted in jQuery onSeptember 11, 2019

这篇文章主要介绍了基于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"});
    }
   });
  }
});

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

jQuery 相关文章推荐
jQuery插件FusionCharts实现的Marimekko图效果示例【附demo源码】
Mar 24 jQuery
jQuery中的deferred使用方法
Mar 27 jQuery
jquery replace方法去空格
May 08 jQuery
JQuery判断正整数整理小结
Aug 21 jQuery
基于jQuery实现Ajax验证用户名是否可用实例
Mar 25 jQuery
基于jQuery实现无缝轮播与左右点击效果
May 13 jQuery
通过jquery.cookie.js实现记住用户名、密码登录功能
Jun 20 jQuery
jQuery实现根据身份证号获取生日、年龄、性别等信息的方法
Jan 09 jQuery
jQuery实现图片下载代码
Jul 18 jQuery
jquery中attr、prop、data区别与用法分析
Sep 25 jQuery
jquery+ajax实现异步上传文件显示进度条
Aug 17 jQuery
jquery实现穿梭框功能
Jan 19 jQuery
html+jQuery实现拖动滑块图片拼图验证码插件【移动端适用】
Sep 10 #jQuery
jQuery实现每日秒杀商品倒计时功能
Sep 06 #jQuery
JS秒杀倒计时功能完整实例【使用jQuery3.1.1】
Sep 03 #jQuery
JavaScript自动生成 年月范围 选择功能完整示例【基于jQuery插件】
Sep 03 #jQuery
Jquery动态列功能完整实例
Aug 30 #jQuery
jQuery - AJAX load() 实例用法详解
Aug 27 #jQuery
jQuery实现判断滚动条滚动到document底部的方法分析
Aug 27 #jQuery
You might like
php数组中删除元素的实现代码
2012/06/22 PHP
PHP正则表达式替换站点关键字链接后空白的解决方法
2014/09/16 PHP
PHP将进程作为守护进程的方法
2015/03/19 PHP
浅谈Laravel队列实现原理解决问题记录
2017/08/19 PHP
JQuery最佳实践之精妙的自定义事件
2010/08/11 Javascript
JavaScript 命名空间 使用介绍
2013/08/29 Javascript
详解JavaScript中基于原型prototype的继承特性
2016/05/05 Javascript
JavaScript实现九九乘法表的简单实例
2016/06/07 Javascript
深入浅析ES6 Class 中的 super 关键字
2017/10/20 Javascript
React BootStrap用户体验框架快速上手
2018/03/06 Javascript
Vue.js自定义事件的表单输入组件方法
2018/03/08 Javascript
微信小程序之判断页面滚动方向的示例代码
2018/08/30 Javascript
jQuery无冲突模式详解
2019/01/17 jQuery
[01:05:40]VG vs Newbee 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
python改变日志(logging)存放位置的示例
2014/03/27 Python
Python开发常用的一些开源Package分享
2015/02/14 Python
python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序
2020/07/20 Python
python3 unicode列表转换为中文的实例
2018/10/26 Python
python 一篇文章搞懂装饰器所有用法(建议收藏)
2019/08/23 Python
Golang GBK转UTF-8的例子
2019/08/26 Python
python中Lambda表达式详解
2019/11/20 Python
tensorflow 获取checkpoint中的变量列表实例
2020/02/11 Python
2020最新pycharm汉化安装(python工程狮亲测有效)
2020/04/26 Python
pip已经安装好第三方库但pycharm中import时还是标红的解决方案
2020/10/09 Python
关于pycharm 切换 python3.9 报错 ‘HTMLParser‘ object has no attribute ‘unescape‘ 的问题
2020/11/24 Python
美国在线宠物商店:Chewy
2019/01/12 全球购物
传统软件工程与面向对象的软件工程有什么区别
2012/05/31 面试题
Python里面如何实现tuple和list的转换
2012/06/13 面试题
行政主管职责范本
2014/03/07 职场文书
领导干部廉政自律承诺书
2014/05/26 职场文书
机械系毕业生求职信
2014/05/28 职场文书
低碳环保标语
2014/06/12 职场文书
2015年个人审计工作总结
2015/04/07 职场文书
网吧员工管理制度
2015/08/05 职场文书
浅谈Nginx 中的两种限流方式
2021/03/31 Servers
Python3 使用pip安装git并获取Yahoo金融数据的操作
2021/04/08 Python