当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue实现带进度条的文件拖动上传功能

Vue实现带进度条的文件拖动上传功能

2018年04月21日  | 移动技术网IT编程  | 我要评论

王老虎抢亲国语,针眼传染吗,谁明浪子心伴奏

1. 基本界面

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport"
   content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="x-ua-compatible" content="ie=edge">
 <link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet">
 <script src="https://cdn.bootcss.com/vue/2.5.13/vue.min.js"></script>
 <style>
  .dropbox {
   border: .25rem dashed #007bff;
   min-height: 5rem;
  }
 </style>
 <title>document</title>
</head>
<body>
<div id="app" class="m-5">
 <div class="dropbox p-3">
  <h2 class="text-center">把要上传的文件拖动到这里</h2>
 </div>
</div>
<script>
 new vue({
  el: '#app',
  data: {},
  methods: {},
  mounted: function () {}
 });
</script>
</body>
</html>

2. 检测拖动事件

首先让页面支持文件拖拽,在 vue 的 mounted() 函数中添加代码:

mounted: function () {
 var dropbox = document.queryselector('.dropbox');
 dropbox.addeventlistener('dragenter', this.ondrag, false);
 dropbox.addeventlistener('dragover', this.ondrag, false);
 dropbox.addeventlistener('drop', this.ondrop, false);
}

当把文件拖动到浏览器的拖动区域时,会触发三种事件:

  1. 文件第一次进入拖动区时,触发 dragenter 事件
  2. 文件在拖动区来回拖拽时,不断触发 dragover 事件
  3. 文件已经在拖动区,并松开鼠标时,触发 drop 事件

实现拖动上传,我们只需要关心 drop 事件。不过另外两个事件也需要监听,目的是阻止浏览器默认行为。如果不阻止,那么把文件拖到浏览器时,浏览器就会自动下载这个文件(默认行为),drop 事件触发不出来。

事件的监听函数添加在 vue 的 methods 对象中:

methods: {
 uploadfile: function (file) {
  console.log(file);
 },
 ondrag: function (e) {
  e.stoppropagation();
  e.preventdefault();
 },
 ondrop: function (e) {
  e.stoppropagation();
  e.preventdefault();
  var dt = e.datatransfer;
  for (var i = 0; i !== dt.files.length; i++) {
   this.uploadfile(dt.files[i]);
  }
 }
},

ondrop() 函数中,通过 e.datatransfer.files 可以拿到用户拖动到浏览器的文件的基本信息,uploadfile() 函数现在只这些信息打印了出来,可以了解到,拖动到浏览器的每个文件都是一个 file 对象:

3. 处理拖动事件

现在,我们要给 uploadfile() 函数增加功能,实现拖动文件时,拖动区出现文件名和一个上传进度条。

首先在 vue 的 data 对象中定义 files 属性,用来保存所有拖动到浏览器中文件的名称。然后在uploadfile() 函数每当被调用时,把文件名和上传进度保存到 files 中:

data: {
 files: []
},
methods: {
 uploadfile: function (file) {
  var item = {
   name: file.name,
   uploadpercentage: 67
  };
  this.files.push(item);
 },
}

上传进度的功能在后面再介绍,先写一个固定值。

相应地,在html代码中,用 v-for 关键字显示 files 的每一项:

<div class="dropbox p-3">
 <h2 class="text-center">把要上传的文件拖动到这里</h2>
 <div class="border m-2 d-inline-block p-4" style="width:15rem" v-for="file in files">
  <h5 class="mt-0">{{ file.name }}</h5>
  <div class="progress">
   <div class="progress-bar progress-bar-striped"
     :style="{ width: file.uploadpercentage+'%' }"></div>
  </div>
 </div>
</div>

而且,“把要上传的文件拖动到这里” 的提示只在拖动区没有文件的时候才显示:

<h2 v-if="files.length===0" class="text-center">把要上传的文件拖动到这里</h2>

这样,拖动效果就有了:

4. 文件上传

接下来实现真正的文件上传,继续往 uploadfile() 函数添加代码:

uploadfile: function (file) {
 var item = {
  name: file.name,
  uploadpercentage: 67
 };
 this.files.push(item);
 var fd = new formdata();
 fd.append('myfile', file);

 var xhr = new xmlhttprequest();
 xhr.open('post', 'upload.php', true);
 xhr.send(fd);
},

这里用到了 formdata,把要上传的文件附在了 formdata 上,并通过ajax方式发送给php端。php端代码:

if (isset($_files['myfile'])) {
 move_uploaded_file($_files['myfile']['tmp_name'], 'uploads/' . $_files['myfile']['name']);
 echo 'ok';
} else {
 echo 'no file specified';
}

现在刷新下页面,把电脑上的两个文件拖到浏览器中,php端会接收并保存文件到 uploads 目录:

提示:如果拖放时遇到php返回了no file specified,或者 $_files 为 null 的情况时,有可能是php限制了post请求最大字节,或者限制了上传文件的体积。这时候需要调整下php.ini中的这两个配置:

post_max_size = 20m // post请求的最大字节数
upload_max_filesize = 20m // 上传文件的最大体积

进度条的展示

基本的上传功能完成了,最后我们来完成进度条。每当ajax请求发送了一段时间的数据时,都会生成一个 progress 事件,我们可以监听 progress 事件来知道当前的上传进度:

uploadfile: function (file) {
  ...
  xhr.upload.addeventlistener('progress', function (e) {
    item.uploadpercentage = math.round((e.loaded * 100) / e.total);
  }, false);
  xhr.send(fd);
},

e.loaded 代表当前ajax发送了多少字节,e.total 代表ajax总共要发送多少字节。通过这两个属性可以计算上传进度的百分比。

这样,一个带进度条的文件拖动上传功能就完成了。

附:完整代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
     content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.bootcss.com/vue/2.5.13/vue.min.js"></script>
  <style>
    .dropbox {
      border: .25rem dashed #007bff;
      min-height: 5rem;
    }
  </style>
  <title>document</title>
</head>
<body>
<div id="app" class="m-5">
  <div class="dropbox p-3">
    <h2 v-if="files.length===0" class="text-center">把要上传的文件拖动到这里</h2>
    <div class="border m-2 d-inline-block p-4" style="width:15rem" v-for="file in files">
      <h5 class="mt-0">{{ file.name }}</h5>
      <div class="progress">
        <div class="progress-bar progress-bar-striped"
           :style="{ width: file.uploadpercentage+'%' }"></div>
      </div>
    </div>
  </div>
</div>
<script>
  new vue({
    el: '#app',
    data: {
      files: []
    },
    methods: {
      uploadfile: function (file) {
        var item = {
          name: file.name,
          uploadpercentage: 0
        };
        this.files.push(item);
        var fd = new formdata();
        fd.append('myfile', file);
        var xhr = new xmlhttprequest();
        xhr.open('post', 'upload.php', true);
        xhr.upload.addeventlistener('progress', function (e) {
          item.uploadpercentage = math.round((e.loaded * 100) / e.total);
        }, false);
        xhr.send(fd);
      },
      ondrag: function (e) {
        e.stoppropagation();
        e.preventdefault();
      },
      ondrop: function (e) {
        e.stoppropagation();
        e.preventdefault();
        var dt = e.datatransfer;
        for (var i = 0; i !== dt.files.length; i++) {
          this.uploadfile(dt.files[i]);
        }
      }
    },
    mounted: function () {
      var dropbox = document.queryselector('.dropbox');
      dropbox.addeventlistener('dragenter', this.ondrag, false);
      dropbox.addeventlistener('dragover', this.ondrag, false);
      dropbox.addeventlistener('drop', this.ondrop, false);
    }
  });
</script>
</body>
</html>

总结

以上所述是小编给大家介绍的vue实现带进度条的文件拖动上传功能,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网