How to Upload Images from React Native (2024)

In this tutorial we'll cover how to upload an image from a React Native app to a remote server.

This is just a high level overview. If you want details (upload progress, setting up a server, multiple images, etc.) please check out our class on Uploading Images in React Native.

With that said, let's get into it.

Tools for Uploading Images in React Native

  • react-native-image-picker. Allows us to access the library of images or the camera.
  • Express + multer: Create a server that can accept image uploads. However you setup the backend the process will be extremely similar.

The Code

Explanation of code below.

// server.jsconst express = require('express');const multer = require('multer');const bodyParser = require('body-parser');const app = express();app.use(bodyParser.json());const storage = multer.diskStorage({ destination(req, file, callback) { callback(null, './images'); }, filename(req, file, callback) { callback(null, `${file.fieldname}_${Date.now()}_${file.originalname}`); },});const upload = multer({ storage });app.get('/', (req, res) => { res.status(200).send('You can post to /api/upload.');});app.post('/api/upload', upload.array('photo', 3), (req, res) => { console.log('file', req.files); console.log('body', req.body); res.status(200).json({ message: 'success!', });});app.listen(process.env.PORT || 3000, () => { console.log( `server is running at http://localhost:${process.env.PORT || 3000}` );});
// App.jsimport React from 'react';import { View, Image, Button, Platform } from 'react-native';import { launchImageLibrary } from 'react-native-image-picker';const SERVER_URL = 'http://localhost:3000';const createFormData = (photo, body = {}) => { const data = new FormData(); data.append('photo', { name: photo.fileName, type: photo.type, uri: Platform.OS === 'ios' ? photo.uri.replace('file://', '') : photo.uri, }); Object.keys(body).forEach((key) => { data.append(key, body[key]); }); return data;};const App = () => { const [photo, setPhoto] = React.useState(null); const handleChoosePhoto = () => { launchImageLibrary({ noData: true }, (response) => { // console.log(response); if (response) { setPhoto(response); } }); }; const handleUploadPhoto = () => { fetch(`${SERVER_URL}/api/upload`, { method: 'POST', body: createFormData(photo, { userId: '123' }), }) .then((response) => response.json()) .then((response) => { console.log('response', response); }) .catch((error) => { console.log('error', error); }); }; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> {photo && ( <> <Image source={{ uri: photo.uri }} style={{ width: 300, height: 300 }} /> <Button title="Upload Photo" onPress={handleUploadPhoto} /> </> )} <Button title="Choose Photo" onPress={handleChoosePhoto} /> </View> );};export default App;

Explanation - server.js. Storing Uploaded Images from React Native

The server sets the ground work for what we're doing so let's talk about that first. It's a standard Express server but our /api/upload path uses the Multer middleware and accepts multipart/form-data. If it sees a name with photo it's going to handle the image upload.

You can check out the multer documentation for details on how it's configured but this will just write files locally to the images/ directory.

The file(s) that were uploaded will be available at request.files and any other data passed will be available at request.body.

Explanation - App.js. Selecting, Formatting, and Uploading Image(s)

Let's look at the handleChoosePhoto function first. In it we open the image library and when a user selects an image we store that in state.

Next is handleUploadPhoto. In it we set up a standard fetch request and set the method to POST, which will call the /api/post route we defined in the server.

What's different is how we pass data in the body field.

If you're anything like me you're used to simply stringifying some JSON (JSON.stringify({ example: true })) and calling it 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.

It will also take any other data you want to pass to it and add it to the form data, as you can see from the userId.

With this the file will be available at request.files and the userId will be available at request.body.userId.

Important Note: Notice that ternary operator in the uri field? We have to do that because iOS prepends the path it returns with a file:// that I've found breaks file uploads so we remove it.

Conclusion

This was a super brief overview of a relatively complex subject. The reality is that uploading an image takes more time than a small JSON object and on mobile networks we have unique challenges to deal with such as:

  • Slow networks
  • No network connection
  • Network connections stopping & starting during upload

These aren't exceptions - they're guarantees that we have to deal with. That's why we cover them in depth in the Uploading Images in React Native class here on React Native School.

If you're interested in going deeper on this subject (or any of the others we cover in our classes) become a member!

How to Upload Images from React Native (2024)

FAQs

How to upload images from React Native? ›

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.

How do I import an image into React Native? ›

App.js
  1. import React, { Component } from 'react';
  2. import {StyleSheet, AppRegistry,Text, View, Image,ImageBackground } from 'react-native';
  3. export default class DisplayAnImage extends Component {
  4. render() {
  5. return (
  6. style={{width: '100%', height: '100%'}}>
  7. <Image source={require('./favicon.png')} />
  8. <Image.

How do I pass an image in React Native? ›

Share an image in a React Native app
  1. First, import the necessary modules from React Native, including the SafeAreaView, TouchableOpacity, StyleSheet, Image, Text, and View components. ...
  2. Create a new functional component called App. ...
  3. In the App component, create a new function called shareImage. ...
  4. Use the Share.
Jan 22, 2023

How to upload a file using Fetch in React Native? ›

Using fetch to send files to server

To upload files with the Fetch API, we need to create a request body that includes the file data. We can do this using the FormData object, which allows us to append file data to a new FormData instance. const file = fileInput. files[0];

How do I download an image from React Native app? ›

You have to use camera roll.
  1. npm install @react-native-community/cameraroll --save.
  2. react-native link @react-native-community/cameraroll.
  3. from: import { CameraRoll } from "react-native"; to. import CameraRoll from "@react-native-community/cameraroll";
Oct 12, 2019

How to load local images in React Native? ›

How to use local Images dynamically in React Native
  1. Ex: const ImageDirectory = “Resources/Images”
  2. const ImageName = currentIndex + “. png” //where current Index will be 1,2 etc.
  3. Const ImagePath = ImageDirectory + ImageName.
May 16, 2020

How to load images in react? ›

The most straightforward way to import an image in React is to import it directly into your component file. This method assumes that the image file is located within your project directory. Here's a code snippet that demonstrates this: import React from 'react'; import myImage from './path_to_your_image.

How to dynamically import images in react? ›

Here is an example of how you can use require. context to import all the images from a folder and display them in a list: // App. js import React from 'react'; import {FlatList, Image, StyleSheet} from 'react-native'; // Import all the images from the assets/images folder const images = require.

How do I select an image in React Native? ›

React Native Image Picker: Allowing your App to Pick Images from the Gallery and Camera
  1. Step 1: Install react-native-image-picker. ...
  2. Step 2: Set the permissions. ...
  3. Step 3: Use React Native Image Picker. ...
  4. Step 4: Directly Launch Camera in the React Native app. ...
  5. Step 5: Directly Launch Image Library in the React Native app.
Aug 2, 2021

How do I add a responsive image in React Native? ›

Therefore, to make the images responsive we can simply set the value of height and width to 100% and resize mode to cover. By setting the Image's height and width to 100% and resize mode to cover, the image will proportionately occupy a 100% of the container's real estate inside of the X and Y-Axis or the container.

How do I pass an image path in React Native? ›

In order for this to work, the image name in require has to be known statically. : require('./my-icon-inactive.png'); <Image source={icon} />; Note that image sources required this way include size (width, height) info for the Image.

How to upload images in React JS? ›

To upload image and preview it using React JS we will use the HTML file input for the image input. After taking input the image url is created using URL. createObjectURL() method and store in the useState variable named file. Display the image as preview using the html img tags with the file url in the src prop.

How to upload image on server in React Native image picker? ›

In this tutorial you will learn how to upload images from your React Native app to a server. We will use Expo to create the app and the ImagePicker and FileSystem modules to select and save images. The images will be saved to the file system of our app and uploaded to a server using the FileSystem. uploadAsync method.

How do I add a local image in React Native? ›

How to use local Images dynamically in React Native
  1. Ex: const ImageDirectory = “Resources/Images”
  2. const ImageName = currentIndex + “. png” //where current Index will be 1,2 etc.
  3. Const ImagePath = ImageDirectory + ImageName.
May 16, 2020

How do I send an image from react? ›

To upload image and preview it using React JS we will use the HTML file input for the image input. After taking input the image url is created using URL. createObjectURL() method and store in the useState variable named file. Display the image as preview using the html img tags with the file url in the src prop.

Top Articles
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 5973

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.