Uploading images from React Native to your server

Eleni Chappen
20spokes Whiteboard
1 min readAug 25, 2017

If you’ve ever felt the need to convert an image in React Native to base64 in order to upload it to your server, there may be a better way.

We typically use react-native-camera for our photo-taking needs. With this package, you can store images on a device in a few ways. We use the option to save the image to disk if we plan to upload it:

<Camera captureTarget={Camera.constants.CaptureTarget.disk} ... >

The data returned from capturing an image will be a file path to your saved image, something like:

var filePath = 'Developer/CoreSimulator/Devices/8B8CBF19-7B64-4C21-8FFF-BB835254C77D/data/Containers/Data/Application/EE3FFDA1-A0FC-43F4-85A8-435CDA35731A/Documents/test.pdf';

When it’s time to send the image to your server, create a new FormData object using this file path:

var data = new FormData();
data.append('my_photo', {
uri: filePath, // your file path string
name: 'my_photo.jpg',
type: 'image/jpg'
}

Then for your request, set the body to this data object:

fetch(path, {
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
method: 'POST',
body: data
});

By uploading images this way, we don’t have to configure our server image libraries (like Paperclip) to handle base64, saving us time and effort.

--

--