I am attempting to upload an image file from react native to my php server. My problem is how to post a file object to php.
My javascript code:
storePicture(){
const file = {
uri: this.state.selected[0].uri,
name: this.state.selected[0].filename,
type: 'image/jpg'
}
fetch('http://localhost:8888/s3/index.php', {
method: 'POST',
body: JSON.stringify({
file: file
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.status)
})
}
My PHP code:
$data_back = json_decode(file_get_contents('php://input'));
$file = $data_back->{"file"};
You cannot stringify like that. Try to create a FormData object, append the file to it and add the FormData to body.
let formData = new FormData();
formData.append("image", this.state.fileInputElement.files[0]);
fetch('http://localhost:8888/s3/index.php', {
method: 'POST',
body: formData
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.