[英]How to upload an Image in React Native
我正在尝试上传图片但我失败了,因为我是 React Native 的新手。 实际上,我想选择一张照片,然后将它上传到我的服务器,从应用程序它不起作用。 当我从邮递员那里尝试它时,它可以工作。 在邮递员中,我选择了form-data
,在键中,当我点击提交时,我选择了类型作为file
,然后图像成功上传,但是当我从应用程序尝试它时,它不起作用。 有人可以帮助我如何实现我的目标。
代码
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
quality: 1,
allowsMultipleSelection: true,
base64: true,
});
let pickerResult = await ImagePicker.launchImageLibraryAsync();
if (!result.cancelled) {
console.log('iff')
ext = result.uri.split('.').pop()
this.setState(prevState => ({
images: [...prevState.images, `data:image/${ext};base64,` + result.base64],
imageView: true
})
)
axios.post(`${apiUrl}/api/cloud/image`,{image:pickerResult})
.then(res=> {
console.log('@@@@@@ response',res.data)
})
.catch(error=> {
console.log('@@@@@@ error reponse',error.response.data)
})
// console.log('fffe', this.state.images)
// this.props.dispatch(uploadImage(this.state.images))
} else {
console.log('else')
}
};
更新:现在的问题是发送文件的大小太大。 所以建议大家不要选择MultiImage,先把画质调低。
所以,我稍微修改一下代码:
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
quality: 0.1,
allowsMultipleSelection: false,
base64: true,
});
if (!result.cancelled) {
let fd = new FormData()
fd.append('imageKey',result.uri); /// file refer to result.uri
axios({
method: 'post',
url: `${apiUrl}/api/cloud/image`,
data: fd,
})
.then(res=> {
console.log('@@@@@@ response',res.data)
})
.catch(error=> {
console.log('@@@@@@ error reponse',error.response.data)
})
// console.log('fffe', this.state.images)
// this.props.dispatch(uploadImage(this.state.images))
} else {
console.log('else')
}
}
解决方案参考: axios post请求发送表单数据。
试试表格数据:
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
quality: 1,
allowsMultipleSelection: true,
base64: true,
});
let pickerResult = await ImagePicker.launchImageLibraryAsync();
///////// assume that pickerResult return image file......
if (!result.cancelled) {
console.log('iff')
ext = result.uri.split('.').pop()
this.setState(prevState => ({
images: [...prevState.images, `data:image/${ext};base64,` + result.base64],
imageView: true
})
)
let fd = new FormData()
fd.append('imageKey',pickerResult);
axios({
method: 'post',
url: `${apiUrl}/api/cloud/image`,
data: fd,
})
.then(res=> {
console.log('@@@@@@ response',res.data)
})
.catch(error=> {
console.log('@@@@@@ error reponse',error.response.data)
})
// console.log('fffe', this.state.images)
// this.props.dispatch(uploadImage(this.state.images))
} else {
console.log('else')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.