这里只贴核心代码,其余的可自行查资料
主要有两个事件:
1、上传文件之前(需要把选择的文件存起来)
2、发送请求(把文件带上就OK)
// 上传文件之前事件
befores = (file, fileList) => {
console.log(file, fileList)
this.setState({
**fileList, // 这里是你选择的文件**
filename: file.name,
loading: -1,
})
return false
}
// 正式上传文件
importXlsOk = e => {
const { fileList } = this.state
const formData = new FormData()
fileList.forEach(file => {
formData.append('file', file) // 这一步很重要**
})
fetch(`${BASE}/api/pc/page/config/stock/importExcel`, {
method: 'POST',
credentials: 'include',
headers: {
// credentials: 'same-origin',
// 'X-Requested-With': null,
// 'Content-Type': 'multipart/form-data' // 不要加上这个文件类型说明
},
body: formData, // 注意
})
.then(res =>
res.json().then(data => {
console.log(data)
...
})
)
.catch(error => {
console.log('Error:', error)
})
}
tips:上传文件的接口如果没有携带cookie的话,可以加上这行试试
headers: {
'X-Requested-With': null,
},