I am trying to capture, and upload an image to a server from react native, however I get the following error when I make the http request:
[TypeError: Network request failed]
Here is my code, I have followed this tutorial:
https://heartbeat.fritz.ai/how-to-upload-images-in-a-react-native-app-4cca03ded855
import React from 'react';
import {View, Image, Button} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default class App extends React.Component {
state = {
photo: null,
};
createFormData = (photo) => {
const data = new FormData();
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android'
? photo.uri
: photo.uri.replace('file://', ''),
});
data.append('id', 1);
return data;
};
handleChoosePhoto = () => {
const options = {
noData: true,
};
ImagePicker.launchImageLibrary(options, (response) => {
if (response.uri) {
this.setState({photo: response});
}
});
};
handleUploadPhoto = () => {
fetch('http://192.168.1.104:3000/', {
method: 'POST',
body: this.createFormData(this.state.photo),
})
.then((response) => response.text())
.then((response) => {
console.log('upload success', response);
})
.catch((error) => {
console.log('upload error', error);
});
};
render() {
const {photo} = this.state;
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{photo && (
<React.Fragment>
<Image
source={{uri: photo.uri}}
style={{width: 300, height: 300}}
/>
<Button title="Upload" onPress={this.handleUploadPhoto} />
</React.Fragment>
)}
<Button title="Choose Photo" onPress={this.handleChoosePhoto} />
</View>
);
}
}
I've tried:
- Add "Content: multipart/form-data" to http request headers
- Add Accept: Accept: application/json" to http request headers
I have noticed that the request fails, only when I add the photo object to the "FormData", that is, the http request runs correctly when I remove the following code:
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android'
? photo.uri
: photo.uri.replace('file://', ''),
});
Edit 02-07-2020
I finally found the solution here:
https://github.com/facebook/react-native/issues/28551#issuecomment-610652110