1

I am using expo for my native application and a firestore database for storage but the thing is I really require a fileserver inside of which I can store an image and get the remote URL and then the remote URL i can put in my firestore db, but can anyone help me as to how can I get a fileserver and how can I use one with node.js

Any answers will be appreciated, Thanks, The Terminal

1 Answers1

0

Here is how you would upload an image from React Native:

import firebase from "firebase/app";
import "firebase/storage";

const storage = firebase.storage();

const urlToBlob = (url) => {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.onerror = reject;
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        resolve(xhr.response);
      }
    };
    xhr.open("GET", url);
    xhr.responseType = "blob"; // convert type
    xhr.send();
  });
};

const uploadImage = async (uri, filename) => {
  const storageRef = storage.ref();

  const imageUri = Platform.OS === "android" ? uri : uri.replace("file://", "");
  const blob = await urlToBlob(imageUri);

  await storageRef
    .child("images/" + filename)
    .put(blob);

  return;
}

// Actuall upload
const fileUri = "file:///var/mobile/Containers/Data/Application/80CD82F2-6626-4828-948E-FC5B1B8236DF/Documents/ExponentExperienceData/user1/images/a12ecb52ce80159a32b142058c059123.jpg"
await uploadImage(fileUri, "a12ecb52ce80159a32b142058c059123.jpg");

and in order to get the file URL (and to download it) you may need this:

import firebase from "firebase/app";
import "firebase/storage";
import * as FileSystem from "expo-file-system";

const storage = firebase.storage();

const downloadImage = async (filepath, targetURI) => {
  const storageRef = storage.ref();
  let downloadURL = false;

  try {
    // Get download link
    downloadURL = await storageRef
      .child(filepath)
      .getDownloadURL();
  } catch (err) {
    // The image doesn't exist remotely
  }

  // Download image
  downloadURL && (await FileSystem.downloadAsync(downloadURL, targetURI));

  return downloadURL;
};

// Actual download
const url = await downloadImage("images/a12ecb52ce80159a32b142058c059123.jpg", FileSystem.documentDirectory + "images/file1.jpg" );

Also from NodeJs you can use: getDownloadURL(); to retrieve the remote url.

human
  • 686
  • 3
  • 9
  • 24
  • Hey, thanks for helping but what I want is the remote URL of the image which should be ending with `.jpg or .png` how can I get that after storing – The Terminal Jun 23 '21 at 17:47
  • see https://stackoverflow.com/questions/42956250/get-download-url-from-file-uploaded-with-cloud-functions-for-firebase – human Jun 23 '21 at 18:34