发布房源——配置ImagePicker-图片上传 & 请求图片路径-headers请求头的写法
配置ImagePicker-图片上传
地址:https://mobile.ant.design/components/image-picker-cn/
- 给 ImagePicker 组件添加 onChange 配置项。
- 通过 onChange 的参数,获取到上传的图片,并存储到状态 tempSlides 中。
handleImage = (files, type, index) => {
// console.log(files, type, index)
this.setState({
tempSlides: files
})
}
打印上传图片信息
请求图片路径
- 根据发布房源接口,最终需要的是:房屋图片路径。 (houses/image)
- 给提交按钮,绑定单击事件。
- 在事件处理程序中,判断是否有房屋图片。
- 如果没有,不做任何处理。
- 如果有,就创建 FormData 的实例对象(form)。
- 遍历 tempSlides 数组,分别将每一个图片对象,添加到 form 中(键为: file,根据接口文档获得)。
- 调用图片上传接口,传递form参数,并设置请求头 Content-Type 为 multipart/form-data。
- 通过接口返回值获取到的图片路径
addHouse = async () => {
const { tempSlides } = this.state
if (tempSlides.length === 0) {
return
} else {
const form = new FormData()
tempSlides.forEach(item => {
form.append('file', item.file)
})
const res = await API.post(`houses/image`, form, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
// console.log(res)
const houseImg = res.data.body.join('|')
console.log(houseImg)
}
}
打印上传图片路径res