Uploading images from React Native to your server

Eleni Chappen
Aug 25, 2017 · 1 min read

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.

20spokes Whiteboard

20spokes Whiteboard is about the entire lifeline of technology startups including development, metrics, business, investing, and more.

)

Eleni Chappen

Written by

Words are things. ~ Maya Angelou

20spokes Whiteboard

20spokes Whiteboard is about the entire lifeline of technology startups including development, metrics, business, investing, and more.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade