我所实现的上传文件样式如下:
HTML代码:
<el-form
:model="file"
ref="form"
label-width="200px"
style="display: flex; justify-content: center; margin-left: -200px"
>
<el-form-item label="上传excel文件:">
<el-input class="aaa" v-model="file.name" :readonly="true"></el-input>
<el-upload
class="upload-demo"
ref="upload"
action="#"
accept=".xls,.xlsx"
:file-list="fileList"
:http-request="httpRequest"
:auto-upload="false"
:show-file-list="false"
:before-upload="beforeUpload"
:on-change="onChange"
>
<el-button slot="trigger" size="small">浏览...</el-button>
<el-button
style="margin-left: 10px; position: absolute"
size="small"
type="primary"
@click="submitUpload"
>上传</el-button
>
</el-upload>
</el-form-item>
</el-form>
定义参数:
data() {
return {
file: {
name: null
},
fileList: []
};
},
methods方法:
//上传文件
submitUpload() {
this.$refs.upload.submit();
},
//上传服务器
httpRequest(params) {
// console.log(params.file); //拿到上传的文件
var formdata = new FormData();
formdata.append("file", params.file);
uploadExcel(formdata).then(res => {
console.log(res);
if (res.code === "0") {
Notification.success({
title: "文件上传成功"
});
this.file.name = null;
this.fileList = [];
} else if (res.code === "-1") {
Notification.error({
title: res.data
});
this.file.name = null;
this.fileList = [];
}
});
},
onChange(file, fileList) {
if (fileList.length > 1 && file.status !== "fail") {
fileList.splice(0, 1);
} else if (file.status === "fail") {
this.$message.error("上传失败,请重新上传!");
fileList.splice(0, 1);
}
this.file.name = file.name;
},
// 上传之前限制文件格式
beforeUpload(file) {
let index = file.name.lastIndexOf(".");
let Xls = file.name.substring(index + 1, file.name.length);
if (Xls === "xls" || Xls === "xlsx") {
return file;
} else {
this.$message.error("仅支持上传excel文件");
return false;
}
}
CSS代码:
::v-deep .el-form-item__label {
font-size: 12px;
font-weight: normal;
}
::v-deep .el-form-item__content {
text-align: left;
}
::v-deep .el-input {
width: 300px;
}
::v-deep .el-input__inner {
font-size: 12px;
}
::v-deep .upload-demo {
display: inline;
margin-left: -30px;
position: absolute;
}
.form-button {
text-align: center;
::v-deep .el-button {
font-size: 12px;
}
}
.el-button--small {
padding: 11px 15px;
}