iview upload组件手动控制上传,这里我只需要将文件的file传给后端用来做excel表格的导入,所以用不到upload-success回调,也用不到action
(iview 有提供excel表格导入的插件)
<Upload :before-upload="handleUpload" :action="``" name="files">
<Button>选择文件</Button>
<span>{{importEqFile.name}}</span>
</Upload>
这里有两点要注意
- 拿到upload组件返回的file再传给后端需要转为formData对象。
这个formData用console.log是打印不出来的,直接传给后端就好
(作为一名小白不知道这一点真的浪费了好久时间) - 传file时的接口请求需要设置另外的请求头:
headers: { ‘Content-Type’: ‘multipart/form-data’ },
handleUpload (file) {
let fd = new FormData()
fd.append('file', file)
fd.append('devTypeL1', this.inspInfos.devTypeL1)
fd.append('unitId', this.inspInfos.unitId)
this.importOk(fd)
return false
},
//调后端接口
async importOk (fd) {
await getImportDevExcel(fd).then((res) => {
this.table.data = [...(res.data || [])].map(item => {
let newA1 = {}
for (const akey in item) {
newA1[this.upperCase(akey)] = item[akey]
}
return newA1
})
}
},
这样就可以正常的获取后端返回的数据啦,我是要用来导入表格数据,把返回的值设为表格的data就好了,如果后端返回的是code_id这种带下划线的key,要把它转换为驼峰命名法,转驼峰的方法:
// 转驼峰
upperCase (str) {
let newStr = [...str.split('_')].map((item, index) => {
if (index) {
item = item.replace(item[0], item[0].toUpperCase())
}
return item
})
return newStr.join('')
},
功能完成 。
最后想问大佬们一个问题,Upload组件提供了format来控制上传文件格式的校验,但我这么写校验没生效,后来手写的,是因为不写upload-success就不会触发校验吗,还是有别的原因呢,求解。