系统中文件上传需要耗费部分时间,本文注重前端Vue怎么编写上传功能和显示假进度
1、Vue部分代码如下:
<template>
<div>
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
<el-upload
ref="upload"
:action="''"
:file-list="fileList"
:http-request="getFile"
accept=".xlsx"
:on-remove="handleRemove"
:on-change="handleChange"
:before-upload="beforeUpload"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="upload">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
属性中action设置空,限制上传格式accept,上传限制大小beforeUpload.最重要的是http-request, 用来获取file对象
2、data部分和methods内容
<script>
export default {
data(){
return{
dialogVisible :false,
fileList: [],
}
},
methods:{
beforeUpload(file){
const isLt10M =file.size /1024 /1024 <10;
if(!isLt10M){
this.$message.error("大于10M")
}
return isLt10M
},
handleRemove(file, fileList){
this.file = {};
},
handleChange(file,fileList){
if (fileList.length>1){
fileList.splice(0,1);
}
},
getFile(item){
this.file = item.file;
},
upload(){
const fd = new FormData();
var vm = this;
fd.append("file", vm.file);
fd.append("pid", 111);
if(Object.keys(vm.file) <=0){
vm.$message.warning("文件未选择");
}else{
const config = {headers:{"Content-Type":"multipart/form-data"}};
const rloading = vm.openLoading();
let num = 0;
vm.timer = setInterval(()=>{
rloading.text = "进度" + num + "%";
if (nu>=95){
num = 99;
}else{
num += 5;
}
}, 500);
vm.dialogVisible = false;
vm.$axios.post("/api/upload/", fd, config)
.then(function(res){
if(res.data.code ===0){
rloading.text = "进度" + 100 + "%";
clearInterval(vm.timer);
rloading.close();
}
})
}
}
}
}
</script>
3、uploadf方法说明:
前端要想传递文件流之外的内容,比如项目id等等,使用FormData(),通过fd.append来添加进去
config设置请求头为multipart/form-data。rLoading是main.js设置的loading效果
Vue.prototype.openLoading = function(){
const loading = this.$loading({
lock: true,
text: "正在加载....",
spinner: "el-icon-loading",
background: "rgba(0,0,0,0.7)",
body: true,
})
return loading
}
调用接口vm.$axios.post("/xxx/xxxx", fd, config)来发送数据到后端
4、假显示进度条
通过循环定时来弄一个假的进度条
vm.timer = setInterval(()=>{
rloading.text = "进度" + num + "%";
if (num>=95){
num = 99;
}else{
num += 5;
}
}, 500);
每隔0.5秒数值加5.到95的时候,直接写死99.如果任务时间长的。就一直在99%位置转圈了。
到接口返回数据时,显示100%。和清除定时器
下一篇博客说明,文件下载导出前端和后端怎么处理,并显示真实进度
本文介绍如何在Vue中实现文件上传功能,包括设置上传限制、使用http-request获取file对象,以及利用FormData传递额外信息。同时,通过模拟进度条展示假进度,实际进度在后端返回数据时更新至100%。下篇博客将探讨文件下载和真实进度显示。
3072

被折叠的 条评论
为什么被折叠?



