模版
<el-upload
class="upload-demo"
ref="upload"
accept=".txt"
action=""
:limit="1"
:http-request="httpRequest"
:auto-upload="false"
:file-list="fileList"
:on-change="handleFileChange"
>
<el-button slot="trigger" size="small" type="warning" style="margin-top: 6px;">選取文件</el-button>
<div slot="tip" class="el-upload__tip" style="color: #ee4234">
{{ tips }}
</div>
</el-upload>
data
fileList: [],
tips: "只能上傳txt格式的文件",
methods
handleFileChange(file, fileList) {
let that = this;
that.beforeUpload(file);
that.file= file;
that.fileList = [fileList[fileList.length - 1]]; // 這一步通惫,是 展示最后一次選擇的dat文件
if (that.fileList.length) {
let params = new FormData();
that.fileList.forEach(item => {
params.append("MultipartFile", item.raw)
})
var config = {
// 添加請求頭
headers: {
"Content-Type": "multipart/form-data;"
},
};
API.addDamageDegree(params, config).then(function (res) {
if (res.code == "200") {
that.isVisible = false
that.$emit('success')
} else {
that.$message.error({
showClose: true,
message: res.data.message,
duration: 5000,
});
}
})
.catch(function (error) {
that.buttonLoading = false;
that.$message.error({
showClose: true,
message: "請求出現(xiàn)異常",
duration: 2000,
});
});
}
},
httpRequest(param) {
let fileObj = param.file; // 相當(dāng)于input里取得的files
let fileName = fileObj.name;
let formData = new FormData(); // FormData 對象
formData.append("MultipartFile", fileObj); // 文件對象
formData.append("fileCreateName", fileName);
this.$emit("upload", formData);
},
isFormatValid(type) {
let pStrDAt = /\.txt?$/i;
return pStrDAt.test(type);
},
beforeUpload(file) {
let fileName = file.name;
// this.$emit("update:fileName", fileName);
let isDat = this.isFormatValid(fileName);
if (!isDat) {
this.tips = "當(dāng)前選擇的文件格式不正確檩咱,請重新選擇!";
} else {
this.tips = "";
}
return isDat;
},