注意:element-ui默认封装的传递文件名为file,与后端起的名字要一致
每次只能上传一个文件,多个文件同时上传的话,会多次调用接口,发多次请求
html:
<el-form-item label="选择文件:" prop="fileList">
<el-upload
class="upload-demo"
ref="upload"
action="/mgmt/FinancialDetailMgmtAdd.do"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:limit="1"
:on-exceed="handleExceed"
accept=".xlsx, .xls"
:data="params"
:on-success="handleFileSuccess"
:auto-upload="false"
:before-upload="beforeAvatarUpload"
>
<el-button slot="trigger" size="small" type="primary"
>选择文件</el-button
>
<el-button
style="margin-left: 10px;"
size="small"
type="success"
@click="submitUpload"
>上传</el-button
>
<div slot="tip" class="el-upload__tip">
只能上传xls/xlsx格式文件
</div>
</el-upload>
</el-form-item>
js:
<script>
export default {
data() {
return {
limit: "1",
fileList: [],
};
},
methods: {
// 文件上传
submitUpload(file) {
this.$refs.upload.submit();
},
handleRemove(file, fileList) {
// console.log(file, fileList);
this.flag = false;
this.fileList = [];
},
handleExceed(files, fileList) {
this.$message.warning(`最多上传 ${this.limit} 个文件。`);
},
handlePreview(file) {
// console.log(file);
},
handleFileSuccess(response, file, fileList) {
console.log("hhhhhhhhhhhhhhh");
console.log(response.jsonError);
if (response.jsonError) {
this.fileList = [];
this.$message.error(
`上传失败,${response.jsonError[0]._exceptionMessageCode}`
);
} else if (response.state === true) {
this._JnlNo = response._JnlNo;
this.fileList.push(file);
this.flag = true;
console.log("成功了");
} else {
this.fileList = [];
this.$message.error(`上传失败`);
}
// this.upload.open = false;
// this.upload.isUploading = false;
// this.$refs.upload.clearFiles();
},
beforeAvatarUpload(file) {
var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
// console.log(testmsg);
const extension = testmsg === "xls";
const extension2 = testmsg === "xlsx";
// const isLt2M = file.size / 1024 / 1024 < 10;
if (!extension && !extension2) {
// console.log(11111111);
this.$message({
message: "上传文件只能是 xls、xlsx格式!",
type: "warning"
});
}
// if (!isLt2M) {
// this.$message({
// message: "上传文件大小不能超过 10MB!",
// type: "warning"
// });
// }
// return extension || (extension2 && isLt2M);
return extension || extension2;
},
}
};
</script>