How can I upload a file in react-native in the most easy way to the server? There is online too much information and libraries, thus I don't know if they're safe to use.
Thank you.
In order to upload files, the 'content-type' header must be set to 'multipart/form-data'. new FormData() creates a new empty formData object that we send as the payload in our POST request. Our POST request assumes there is an API endpoint on our backend server at http://localhost:3000/uploadFile. We're done!
To handle image uploads we need to set the encoding type to multipart/form-data which means we need to format our data differently. Thus the createFormData function. This function will go ahead and take the image we selected and add it to the photo field of the form data with the required info.
This is the method to upload file to server using fetch
const body = new FormData();
//String Key value pair appending to body
body.append('KEY', VALUE);
body.append('KEY', VALUE);
body.append('KEY', VALUE);
//Appending file to body
body.append(KEY_AS REQUIRED_IN_SERVICE, {
uri: PASS_URI_OF_THE_FILE,
type: 'image/jpeg', //This is the file type .. you can define according to your requirement
name: 'photo.jpg', //File name you want to pass
})
//Service call
fetch(YOUR_URL, {
method: 'POST',
headers: new Headers({
YOUR_HEADER_PARAMS
}),
body: body
})
.then(res => res.json())
.then((responseJson) => {
//GET RESPONSE SUCCESS OF FAILURE
})
.catch((error) => {
//ERROR
});
}
give a try https://github.com/itinance/react-native-fs
we use in production in some apps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With