先上传文件,第一个接口会返回一个文件id,用文件id调用第二个接口,会返回文件进度。
200毫秒轮询一次,当进度接口返回100时,取消轮询。
<div class="flex-wrap">
<i
class="iconfont icon-wenjianshangchuan gc-ft-shallowGray"
:class="isUp ? 'green' : ''"
></i>
<p class="tip">2.上传填写好的文件,仅支持XLS、XLSX格式文件</p>
<p class="txt" v-if="isUp">{{ fileName }}</p>
<p class="txt">
<el-progress
v-if="isImport"
:percentage="percentage"
color="#61C5C1"
></el-progress>
</p>
<el-button
v-if="!isImport"
slot="trigger"
@click="creatiptFile"
:class="isUp ? 'updata' : ''"
>{{ isUp ? "重新上传" : "上传文件" }}</el-button
>
<el-button
v-if="isUp && !isImport"
type="success"
@click="uploadFile"
>确认导入</el-button
>
<el-button v-if="isImport" :loading="true" type="success"
>导入中</el-button
>
</div>
data() {
return {
header_title: "批量添加",
isUp: false,
isImport: false,
fileName: "",
percentage: 0,
};
},
methods: {
creatiptFile() {
this.percentage = 0;
let _this = this;
let input = document.createElement("input");
input.type = "file";
input.accept = ".xls,.xlsx";
input.click();
input.onchange = function (res) {
console.log(input.files);
_this.isUp = true;
_this.fileName = input.files[0].name;
_this.fileObj = input.files;
};
},
uploadFile() {
let that = this;
let form = new FormData(); // FormData 对象
let blob = new Blob([this.fileObj[0]]);
form.append("file", blob, this.fileObj[0].name);
this.isImport = true;
this.isUp = false;
if (that.isImport) that.getimport(form);
},
getimport(form) {
let that = this;
httpApi
.import(form)
.then((res) => {
if (res.code == 200) {
let config = {
product_id: res.data.product_id,
};
that.getSchedule(config);
} else {
this.isImport = false;
//失败
}
})
.catch((err) => {
that.isImport = false;
this.$message.info(err.message);
});
},
getSchedule(config) {
let that = this;
httpImport.getSchedule(config).then((res) => {
if (res.code == 200) {
this.percentage = res.data.percent;
if (res.data.percent == 100) {
setTimeout(function () {
that.isImport = false;
}, 200);
} else {
setTimeout(function () {
if (that.isImport) that.getSchedule(config);
}, 500);
}
} else {
console.log("上传成功")
}
});
},
效果如下