總結:type類型是file的input框上傳的文件,都可以用formData對象上傳,我的代碼很簡單,非常簡單,very簡單,沒有網上的複雜,所以分享出來,供大家參考。
1.接口部分
注意點1:必須設置headers的content-type爲multipart/form-data,不然後臺會報the current request is not multipart request
注意點2:這裏有兩個參數,第一個是用formData轉化的文件,第二個是以對象傳過來的需要用的字符串
// 客戶-導入客戶
export const apiImportCusExcel = (formData, params) => {
return new Promise((resolve, reject) => {
instance.post(
baseApi+'/api/console/customer/customerImport?customerGroupTypeId='+params.customerGroupTypeId+'&importType='+params.importType+'&isSupplementCustomerInfo='+params.isSupplementCustomerInfo+'&seaId='+params.seaId,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(response => {
resolve(response.data)
})
.catch(error => {
reject(error)
})
})
}
2.數據處理部分
注意點1:文件上傳改變事件的file.raw就是我們要上傳的文件
注意點2:注意點1中的文件用FormData對象append一下,其餘的都是常規的接口數據處理操作。
handleImportCusChange(file, fileList){
let self = this;
self.importCus.fileTemp = file.raw
},
importCusFile() {
let self = this;
let file = self.importCus.fileTemp;
var fileFormData = new FormData();
fileFormData.append('file', file);
let passObj = {
importType: 1,
testId: 3
}
apiImportCusExcel(fileFormData, passObj).then(response => {
if(response.code === abbr.okId){
self.$message({
showClose: true,
message: response.msg,
type: 'success'
});
self.closeModel('addCus');
}else{
self.$message({
showClose: true,
message: response.msg,
type: 'warning'
});
}
}).catch(error => {
})
},
3.頁面部分
注意點1:limit是限制每次可以上傳多少個文件,我的變量設置的1
注意點2:這裏沒有action,因爲我是自定義的上傳方法,不調用組件的submit方法
注意點3:這裏的accept複製的https://segmentfault.com/a/1190000018993619?utm_source=tag-newest#articleHeader2這個分享者所寫的,由於該分享者寫得太複雜,我沒采用,抄了自己以前寫得圖片上傳的代碼
<el-upload ref="importCusBtn"
:on-change="handleImportCusChange"
:limit="importCus.limitUpload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:auto-upload="false">
<el-button size="small" type="primary">點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只 能 上 傳 xlsx / xls 文 件,只能同時導入一個文件哦!</div>
</el-upload>
<el-button type="primary" @click="handleImportCusClick">導入</el-button>