

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实现带进度条的文件拖动上传功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
