Pick local images and upload to backend with API call — React Native
If you are feeling trouble to capture an image or pick from gallery and upload it to backend with rest API.
Packages we will use in guide
I will call API with axios and fetch too. First we will look into react-native-Image-picker.
Let’s add permissions for using camera first.
add following permissions to project root/android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
add following permission string to project root/ios/ProjectName/Info.plist
<!-- Required with iOS 10 and higher -->
<string>We use this permission to... (purpose)</string>
<!-- Required with iOS 11 and higher: include this only if you are planning to use the camera roll -->
<string>We use photo add from library for .. (purpose)</string>
<!-- Include this only if you are planning to use the camera roll -->
<string>We use photo library for .. (purpose)</string>
<!-- Include this only if you are planning to use the microphone for video recording -->
<string>We use micro phone for .. (purpose)</string>
Pick Image from Image Gallery
Skip the alert dialog and launch the camera directly.
Skip the alert dialog and launch the image library directly.
At this point you have picked you image with ImagePicker from Camera or Image Gallery.
Now we will see how we can upload this image to server by calling Rest API from app side. To upload local images we will check How to use FormData for File Uploading in React Native?
- Create FormData by creating an object and appending the values you want to send to the server
You can append any other data that you need to send to body of API, like if you need to send what category of image it is.
Now let’s see how we can call API with formData, first we will see with fetch
If you prefer fetch, at this point your image should be uploaded.
Now we will look how we can use axios to call our Rest API with formData to upload Image.
Please note headers could vary, if your API is working please
That’s it. Thank you for reading.
“Habits are critical because they build consistency and consistency is what makes you reliable.” John Sonmez