项目中需要上传文件,用的vue+elementUI,使用的上传组件是elementUI的el-upload组件,通常用到过的上传方式有两种
1.上传到云服务器,再把返回的连接给后端
2.以formdata的方式直接传给后端
这里使用的是第二种方式手动上传的方式进行上传文件,较为简单。
过多的文字描述让人头大,直接上代码。
<template>
<div class="contain">
//accept为上传的格式
//limit为上传文件限制数
//file-list为上传文件列表
<el-upload
class="upload-demo sendData"
:action="UploadUrl()"
accept=".xls"
:on-preview="handlePreview"
:on-change="fileChange"
:before-remove="beforeRemove"
:limit="1"
:http-request="uploadFile"
:auto-upload="true"
:on-exceed="handleExceed"
:file-list="fileList"
>
<el-button size="small" type="primary" class="dataSendBtn">上传数据</el-button>
<!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [],
};
},
created() {
this.readExcel();
},
methods: {
UploadUrl() {
// 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
return '';
},
fileChange(file, fileList) {
this.fileList.push(file.raw);
console.log(this.fileList);
},
handleCurrentChange() {},
handleSizeChange() {},
sendData() {
console.log('sadsad');
},
uploadFile(val) {
if (this.fileList.length === 0) {
this.$message.warning('请上传文件');
} else {
const form = new FormData();
// file和flag分别为后端要求上传的参数名,类似于post、get等请求中的参数
form.append('file', val.file);
form.append('flag', true);
this.fileList = [];
this.$api
.post('/import/upload', form)
.then((res) => {
console.log(res);
if (res) {
console.log(res);
this.$message({
message: '上传成功',
type: 'success',
});
} else {
console.log(res);
}
})
.catch((res) => {
console.log(res);
});
}
},
handlePreview(file) {
console.log(file);
},
// 文件限制钩子函数
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件,请刷新页面后重试。`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
},
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__headerbtn {
display: none;
}
.sendData {
position: absolute;
right: 0px;
top: -40px;
width: 120px;
height: 30px;
}
.dataSendBtn {
width: 120px;
}
.contain {
position: relative;
}
</style>