好記性不如爛筆頭,還是老實記錄下。
我這邊上傳檔案是統一通過表單送出上去,不是單獨上傳檔案。是以用
var formdata = new FormData();
對象來上傳表單以及檔案。
其中的一個需要上傳的檔案,(目前隻能上傳一個)。
<el-form-item label="導入資産表:" :label-width="formLabelWidth1" prop="uploadMaterialFile">
<el-upload ref="uploadMaterialFile" action="" :on-change="uploadChange" :auto-upload="false" >
<el-button type="primary" size="mini">上傳</el-button>
</el-upload>
</el-form-item>
on-change對應的方法以及表單rules驗證的方法
uploadChange:function(file,filelist){
if(filelist.length && filelist.length >=1 ){
/**引用對象然後驗證表單域-這個可以清除上一步不通過時的提示*/
this.$refs.formMap.validateField('uploadMaterialFile');
}
if(filelist.length>1){
filelist.splice(0,1);
}
this.$refs.uploadMaterialFile.$el.children[0].children[1].value = "";
},
/* 表單驗證的方法**/
validateFile: function (rule, value, callback) {
if (!this.$refs.uploadMaterialFile.uploadFiles.length) {
callback(new Error('請選擇要上傳的檔案'));
// } else if (this.$refs.uploadMaterialFile.uploadFiles.length > 1) {
// callback(new Error('每次上傳隻支援一個檔案'));
} else {
var regx = new RegExp("(.xlsx)$|(.doc)$|(.docx)$|(.xls)$");
/**這裡有個坑,單檔案上傳,第一次上傳錯誤格式接着上傳第二次格式,清單中數組值有兩個*/
if (!regx.test(this.$refs.uploadMaterialFile.uploadFiles[this.$refs.uploadMaterialFile.uploadFiles.length-1].name)) {
callback(new Error('檔案格式隻支援xlsx、doc、docx、xls'));
}
callback();
}
},
在表單rules中需要
uploadMaterialFile:[{validator: this.validateFile}],
最後在送出中使用formdata送出
saveCheckOper(){
var self = this;
this.$refs.formMap.validate((valid) => {
if (valid) {
var formData = new FormData();
formData.append("formMap", JSON.stringify(this.formMap))
for(let i = 0;i < this.$refs.uploadMaterialFile1.uploadFiles.length;i++){
// formData.append("uploadFiles[]", typeof this.WebData[i].uploadFile == 'string' ? noChangeFile : this.WebData.uploadFile ? this.WebData[i].uploadFile : emptyFile)
formData.append("file", this.$refs.uploadMaterialFile1.uploadFiles[i].raw)
formData.append("fileName", this.$refs.uploadMaterialFile1.uploadFiles[i].name)
}
formData.append("assetFile", this.$refs.uploadMaterialFile.uploadFiles[0].raw)
formData.append("assetFileName", this.$refs.uploadMaterialFile.uploadFiles[0].name)
this.loading = true;
this.$fetch.addSafeCheck(formData).then((resp) => {
if (resp.data.returnCode == "0") {
// self.dialogFormVisible = false;
this.closeCheckOperDialog();
self.search();
self.$message.success('操作成功')
}
this.loading = false;
}, (error) => {
console.log(error);
this.loading = false;
})
}
})
},