I have a react-native app where I used react-native-image-picker to take image from gallery and it successfully taken and preview on image tag. But failed to submit the image on laravel API.
- Node version: 16.13.2
- npm version: 8.1.2
- react-native-cli version: 2.0.1
- react-native version: 0.66.1
react-native code for image-pick is given below:
`<TouchableOpacity
style={styles.fileInput}
onPress={() => {
let options = {
storageOptions: {
path: 'images',
},
};
launchImageLibrary(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
setDocument(response.assets[0].uri)
setFromImage({
uri: response.assets[0].uri,
type: response.assets[0].type,
name: response.assets[0].fileName,
// data: response.data
data: response.assets[0].uri
})
console.log(fromImage);
}
});
}}>
<Text style={{textAlign: 'center', color: '#00549F', fontSize: 16,fontWeight: 'bold',}}>
<Icon name='file' type='font-awesome' color='#00549F' /> Choose File
</Text>
</TouchableOpacity>`
react-native code for Laravel API submit is given below:
`<TouchableOpacity style={styles.button} onPress={() => {
const url = appUrl.testImageStore;
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'enctype': 'multipart/form-data',
},
body: JSON.stringify({
document: fromImage,
}),
};
fetch(url, config)
.then(response => response.json())
.then(responseJson => {
// console.log(responseJson)
if (responseJson.status == '2') {
Alert.alert(responseJson.message);
} else if (responseJson.status == '1') {
Alert.alert(responseJson.message);
// navigation.navigate('Home');
} else if (responseJson.status == '0') {
Alert.alert(responseJson.message);
// } else if (responseJson.status == '3') {
// setErrorMessages(responseJson.messages.toArray())
// Alert.alert(responseJson.messages);
}
})
.catch(error => {
//Alert.alert("Failed to registration 2");
});
}}>
<Text style={{textAlign: 'center', color: 'white', fontSize: 16}}>
Submit
</Text>
</TouchableOpacity>`
Laravel API code is given below:
`public function testImageStore(Request $request){
if($request->hasFile('document')){
$image = $request->file('document');
$folder_path = 'uploads/images/documents/';
$image_new_name = Str::random(20).'-'.now()->timestamp.'.'.$image->getClientOriginalExtension();
//resize and save to server
Image::make($image->getRealPath())->save($folder_path.$image_new_name);
return response()->json([
"message"=>"file found & stored",
"status"=>"1",
]);
}
return response()->json([`enter code here`
"message"=>"file not found",
"status"=>"1",
]);
}`
After submitting image it don't found and the output screen is given attached file, please concern there.
CLICK HERE to see the output
CodePudding user response:
react-native-image-picker returns image URI reference to the device media storage not actually image data.
You have 2 options to get real image data:
- Set
includeBase64property totrueand uploadbase64image data - Fetch image data as BLOB format and upload BLOB data
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", localPath, true);
xhr.send(null);
});
// Code to upload to BLOB data to the server here
// We're done with the blob, close and release it
blob.close();
