How to upload images to firebase from a native React app


If you are building a mobile or web application, you will typically need some type of hosting service to manage application data, upload and manage files, and possibly perform social authentication with third parties such as Google, Facebook, and GitHub.

Firebase is a cloud-based hosting platform that lets you do all of that and more. Firebase Storage is used to securely upload your Firebase apps and download them into apps.

In this post, you will create a React Native application with the ability to upload images to Firebase Storage.

If you don’t have a Firebase account yet, you can create one on the Firebase home page. Once your account is set up, go to your Firebase console and click Add project button to add a new project.

Enter your project details and click Create project button when finished. On the next page, select the web option (i.e. the icon). This will take you to Add Firebase to your web app page.

Provide a nickname for your app, then click Register the app. On the following page, you’ll be provided with the Firebase SDK installation command and the details you need to include in your app’s configuration file to connect it to Firebase.

Make sure you copy all of this configuration to an accessible location as you will be using it later.

That’s it for Firebase. Now let’s create the UI to load the image from our React Native app.

React native app development

Prerequisites

To follow this tutorial, you will need:

  • At least a basic understanding of React Native
  • Set up Expo or React Native CLI on your local development machine
  • If you’re using the React Native CLI, you need to have XCode or Android Studio installed to run the emulator.
  • Install firebase with npm install firebase.

Open your React Native project with Visual Studio Code (or another IDE). Go inside the /components folder and create a new file called UploadScreen.js.

Open the file and import the following:

1
  import React, {useState} from 'react'
2
    import {View, StyleSheet, Image, Text, TouchableOpacity, SafeAreaView, Alert} from 'react-native'
3
    import * as ImagePicker from 'expo-image-picker'
4
    import {firebase} from '../config' 

After that, create a file UploadScreen function component and return an empty <SafeAreaView> currently. Also export the function at the bottom of the file:

1
const UploadScreen = () => {
2
    return(
3
        <SafeAreaView>
4
          // view will go here
5
        </SafeAreaView>
6
    )
7
}
8
export default UploadScreen;

Just above the return instruction, create the file image AND loading status and set them to null TO false initially:

1
   const [image, setImage] = useState(null)
2
   const [uploading, setUploading] = useState(false) 

Create the function pickImage. When invoked, this feature launches your device’s image library so you can choose your image. After the image is fetched, we store it in the calling state setImage:

1
    const pickImage = async () => {
2
        let result = await ImagePicker.launchImageLibraryAsync({
3
            mediaTypes: ImagePicker.MediaTypeOptions.All,
4
            allowsEditing: true,
5
            aspect: [4,3],
6
            quality: 1
7
        });
8
        const source = {uri: result.assets[0].uri}
9
        console.log(source)
10
        setImage(source)
11
    }; 

After choosing an image, we then need to upload it to Firebase. The following function takes care of this when invoked:

1
    const uploadImage = async () => {
2
        setUploading(true)
3
        const response = await fetch(image.uri)
4
        const blob = response.blob()
5
        const filename = image.uri.substring(image.uri.lastIndexOf('/')+1)
6
        var ref = firebase.storage().ref().child(filename).put(blob)
7
        try {
8
            await ref;
9
        } catch (e){
10
            console.log(e)
11
        }
12
        setUploading(false)
13
        Alert.alert(
14
            'Photo uploaded!'
15
        );
16
        setImage(null);
17
    } 

With this code, we get the address of the image and get the name of the file, which we then upload to Firebase. If successful, we trigger an alert that says “Photo Uploaded” and reset the status of the image. However, if an error occurs, we log it to the console.

Next, we show the view of ours UploadScreen component. Copy and paste the following code into the file return() declaration of UploadScreen function:

1
<SafeAreaView style={styles.container}>
2
  <TouchableOpacity style={styles.selectButton} onPress={pickImage}>
3
    <Text style={styles.btnText}>Pick an Image</Text>
4
  </TouchableOpacity>   
5
  <View style={styles.imageContainer}>
6
   {image && <Image source={{uri: image.uri}} style={{width: 300, height: 300}}/>}            
7
  <TouchableOpacity style={styles.uploadButton} onPress={uploadImage}>
8
      <Text style={styles.btnText}>Upload Image</Text>
9
  </TouchableOpacity>
10
  </View>            
11
</SafeAreaView>

In the above code we define two buttons:

  • One to choose an image (clicking this button invokes pickImage)
  • The other to upload the image to firebase (pressing this invokes uploadImage)

Save the changes to the file.

Finally, enter App.js and use the following code:

1
import * as React from 'react';
2
import { View, StyleSheet } from 'react-native';
3
import UploadScreen from './components/UploadScreen';
4

5
export default function App() {
6
  return (
7
    <View style={styles.container}>
8
      <UploadScreen />
9
    </View>
10
  );
11
}
12

13
const styles = StyleSheet.create({
14
  container: {
15
    flex: 1
16
  }

Save the file and check your device/emulator. You should find the following rendered UI on your device.

Final view of the appFinal view of the app
Final view of the app

Click the Choose an image button, select an image from your device and click Upload image to upload it to firebase.

Go to your Firebase archive and confirm that the image has been uploaded.

Image in FirebaseImage in FirebaseImage in Firebase
Image in Firebase

As you can see above, mine loaded fine.

Now that you know how to upload an image, you can use this knowledge to create even more exciting projects with React Native. For example, you can list your digital products or more premium access options (e.g. amount of extra coins for a game) which can be unlocked through in-app purchases.

Conclusion

As a developer, Firebase offers you many features, including file uploads with storage. Uploading files to Firebase requires setting up a web application in Firebase. At the end of this process, you get the configurations to connect your React Native app to Firebase.

I hope you found this article useful. You can also learn how to upload images to Firebase from an Android app.



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *