0
0
React Nativemobile~5 mins

Cloud Storage in React Native

Choose your learning style9 modes available
Introduction

Cloud Storage lets your app save files like photos or documents online. This way, users can access their files from any device anytime.

You want users to upload and save photos in your app.
Your app needs to store documents or files that users can download later.
You want to keep user data safe even if they delete the app.
You want to share files between users or devices easily.
You want to back up app data without using the device storage.
Syntax
React Native
import storage from '@react-native-firebase/storage';

// Upload a file
const reference = storage().ref('path/to/file.jpg');
await reference.putFile(localFilePath);

// Download a file URL
const url = await reference.getDownloadURL();
Use ref('path') to point to where the file is stored in the cloud.
Use putFile(localPath) to upload a file from the device.
Examples
This uploads a photo from the device to the cloud under 'images/photo1.jpg'.
React Native
const reference = storage().ref('images/photo1.jpg');
await reference.putFile('/local/path/photo1.jpg');
This gets a web link to download the 'report.pdf' file stored in the cloud.
React Native
const reference = storage().ref('docs/report.pdf');
const url = await reference.getDownloadURL();
Sample App

This app has a button to upload a local image to cloud storage. After uploading, it shows the image from the cloud using the download URL.

React Native
import React, {useState} from 'react';
import {View, Button, Image, Text} from 'react-native';
import storage from '@react-native-firebase/storage';

export default function CloudStorageExample() {
  const [imageUrl, setImageUrl] = useState(null);

  async function uploadAndGetUrl() {
    const localPath = '/path/to/local/image.jpg';
    const ref = storage().ref('uploads/myImage.jpg');
    try {
      await ref.putFile(localPath);
      const url = await ref.getDownloadURL();
      setImageUrl(url);
    } catch (e) {
      setImageUrl(null);
    }
  }

  return (
    <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
      <Button title="Upload Image" onPress={uploadAndGetUrl} />
      {imageUrl ? <Image source={{uri: imageUrl}} style={{width:200, height:200, marginTop:20}} /> : <Text>No image uploaded yet.</Text>}
    </View>
  );
}
OutputSuccess
Important Notes

Make sure to set up Firebase and add the config files to your React Native project before using cloud storage.

Uploading large files may take time; consider showing a loading indicator in real apps.

Always handle errors like permission issues or network problems gracefully.

Summary

Cloud Storage lets your app save and get files online easily.

Use ref to point to files and putFile to upload.

Get a file's URL with getDownloadURL to display or download it.