这是使用element的文件上传组件
<el-upload
size="small"
class="upload-demo"
drag
:on-change="handleChange"
:file-list="fileList"
action=''
:auto-upload='false'
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<template v-slot:tip>
<div class="el-upload-tip el-upload-tip--small" style="margin-bottom: 20px">
只能上传xls文件,且不超过500kb<a style="cursor: pointer" href="http://kano.guahao-test.com/Wnx42440019?token=Mjk4MzQ4NDUzZDE2NjlhNjRlNTRhYWYwMzFmMDg2YjFfTUQ1COUSTOM"
>点击下载上传模板</a
>
</div>
</template>
</el-upload>
我们需要获取到上传的文件,这里定义了一个空的fileList来保存,怎么获取到这个filelist呢?
就是这个on-change绑定的方法
async handleChange (file) {
this.fileList = [file]
},
接下来是上传后对应的方法,这里使用的是formData的形式提交
async UploadFile () {
if(this.fileList.length <= 0){
this.$message.error('请选择文件');
return
}
const formData = new FormData();
formData.append('file', this.fileList[0].raw)
this.$weRequest('/health/import', {
name: 'upload',
method: 'POST',
requestType: 'form',
data:formData,
hooks: {
success : [
(res) => {
this.failedNum = res.data.errorCount ;
this.sucessNum = res.data.successCount ;
}
],
},
});
this.showResult = true;
},
这里使用的是封装的请求,生成了一个 boundary 字段, Content-Type 里指明了数据是以 mutipart/form-data 来编码
文件上传前格式和文件大小的限制
:before-upload="beforeAvatarUpload"
以支持扩展名:doc .docx .pdf .jpg,文件不超过20M 为例
beforeAvatarUpload(file) {
const type = file.name.split('.');
const isJPG = type[1] === 'jpeg' || type[1] === 'jpg';
const isDoc = type[1] === 'doc';
const isDocx = type[1] === 'docx';
const isPdf = type[1] === 'pdf';
const isLt2M = file.size / 1024 / 1024 < 20;
if (!isJPG && !isDoc && !isDocx && !isPdf) {
this.$message.error('格式不符,请重新选择');
return false
}
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 20MB!');
return false
}
return (isJPG || isDoc || isDocx || isPdf) && isLt2M;
},