Uploading images to Firebase Storage with React-Native (Expo)
In this post I’ll demonstrate how you can upload native media from within a React-Native application to the Firebase Storage Container.
Essentially the ‘magic’ behind this feature can be broken down into 2 steps. The first being acquiring access to the image on the device and the last would be uploading said image to Firebase Storage.
TLDR;
- Access device files using expo-media-library
- Convert files to blobs using the uri and fetch
- Upload blob to a Firebase storage pointer
Accessing native media using React-Native
The Expo environment of React-Native makes this trivial. I highly recommend going through the original docs for this.
Assuming you didn’t go through the docs, what it boils down to is the following:
1. Add the expo-media-library to your project
expo install expo-media-library
2. Import the media-library wherever you need it
import * as MediaLibrary from 'expo-media-library';
3. Acquire user permission
Nowadays users can specify which media items can be accessed by which apps.
// Shows the pop-up asking for permissions to access media
const a = await MediaLibrary.requestPermissionsAsync();// Shows the pop-up asking to select media that can be accessed
const b = await MediaLibrary.presentPermissionsPickerAsync();
4. Profit
Using the statement below you should be able to retrieve all allowed media items of the device.
const assets = await MediaLibrary.getAssetsAsync();
You can further use React-Native to render these images given their file location.
import { Image } from 'react-native';<Image imageSource={{uri: assets[0].uri}} />
Uploading native media to Firebase Storage
Using the official Firebase SDK you can create a reference to a (non-existing) file and put content on that position.
import * as firebase from 'firebase';const storageRef = firebase.storage().ref();
const storageRef.child("image1.jpg");storageRef.put(file);
For this to work the file should be in the format ‘Blob’, ‘Uint8Array’ or ‘ArrayBuffer’. Thus we’ll convert the asset to a blob using fetch.
type File = Blob | Uint8Array | ArrayBuffer;const uri = assets[0].uri;const response = await fetch(uri);
const file: File = await response.blob();
And that is really all there is to it. If everything went correctly you should see the file under the Firebase storage tab in a split-second.