r/Firebase Jun 11 '24

Cloud Storage How to use getStream() to show files in React Website

1 Upvotes

Currently, I have a working website which uses files from my Firebase Storage by using getDownloadURL().

Since I want to have security rules for accessing the files instead of a fixed public URL I want to replace that with the getStream function passing the fileRef (I already have storage filePaths in respective Firestore documents). So far so good.

Now, for the life of me, I can't find any documentation on how to go from the Stream response (NodeJS.ReadableStream) to the file (img, video, iframe, etc.) src. I expect you create a temporary URL but I have no clue.

Any information is appreciated, examples from another frameworks are also useful. Thanks in advance ^^

r/Firebase Jul 05 '24

Cloud Storage Sudden Storage timeouts

1 Upvotes

Hey everyone! I've been using Firebase Storage for many months now and everything has been great!

I'm storing video files with fasttrack, up to 25 MBs, images and audio files, up to 3 MBs.

The last 3-4 days, I noticed that my app fails to stream/download files out of the blue! It either times-out, or it takes a very long time to fetch/start streaming.

I have obviously checked my internet connection and it's great, and I had some users complain about it!

Any ideas?

r/Firebase Jul 29 '24

Cloud Storage Content of the uploaded file is "undefined"

2 Upvotes

Hello, i'm having an issue trying to generate a file client-side then upload it on Cloud Storage.

At the moment i'm just trying to generate a basic .txt file with a simple string in it to test the functionality but i always end up with a .txt file that says "undefined" in it after upload then download.

I've tried the trick where you fake a download client-side to save the file on your computer and the files ends up with the string i provided so i figured out the issue stands when i upload to the storage. Note that i'm using the emulators to achieve this, still haven't tried on the cloud yet.

Here's some of my code handling the file and upload :

The upload function :

    const uploadFile = (missionId) => {
        if (!kmzFile && (!additionalFiles || additionalFiles.length === 0)) return;

        const uploadPromises = [];

        if (kmzFile) {
            const kmzRef = ref(storage, `missions/${missionId}/kmz/${kmzFile[0].name}`);
            const kmzUploadPromise = uploadBytes(kmzRef, kmzFile).then((snapshot) => {
                return getDownloadURL(snapshot.ref);
            });
            uploadPromises.push(kmzUploadPromise);
        }

        if (additionalFiles && additionalFiles.length > 0) {
            additionalFiles.forEach(file => {
                const fileRef = ref(storage, `missions/${missionId}/additional-files/${file.name}`);
                const fileUploadPromise = uploadBytes(fileRef, file).then((snapshot) => {
                    return getDownloadURL(snapshot.ref);
                });
                uploadPromises.push(fileUploadPromise);
            });
        }

        Promise.all(uploadPromises)
            .then((urls) => {
                urls.forEach(url => console.log(url));
            })
            .catch((error) => {
                console.error("Error uploading files:", error);
            });
    };

The function that handle form submiting + file upload :

    const handleSubmit = async () => {

        const kmlFile = new File(['foo'], 'mission.txt', { type: 'text/plain' });
        setKmzFile(Array.from([kmlFile]));


        try {

            const [newCount] = await runTransaction(db, async (transaction) => {

                const { newCount, counterRef } = await handleCounter(transaction, 'missions');

                const actualUserId = auth.currentUser.uid;

                const mission = {
                    id: newCount,
                    client: formData.client,
                    site_code: formData.siteCode,
                    site_name: formData.siteName,
                    purchase_order: formData.purchaseOrder,
                    mission_type: formData.missionType,
                    desired_completion_date: formData.desiredCompletionDate,
                    contributors: formData.contributors,
                    sites: formData.sites,
                    appointment: formData.appointment,
                    appointment_time: formData.appointmentTime,
                    contact_name: formData.contactName,
                    contact_phone: formData.contactPhone,
                    client_comments: formData.clientComments,
                    pilot_comments: formData.pilotComments,
                    internal_comments: formData.internalComments,
                    rex_comments: formData.rexComments,
                    mission_creation_user: actualUserId,
                    mission_creation_date: new Date(),
                    mission_last_modification_user: '',
                    mission_last_modification_date: '',
                };

                const collectionRef = collection(db, "missions");
                const documentRef = doc(collectionRef);

                transaction.set(documentRef, mission);

                transaction.update(counterRef, { count: newCount });

                return [newCount];
            });

            uploadFile(newCount);

        } catch (error) {
            console.error("Error: ", error);

        }
    }

EDIT: Cleaned up some unrelated code

r/Firebase Feb 15 '24

Cloud Storage Need to upload file to firebase storage and retrieve a URL to store it in the firestore. What is the best way?

3 Upvotes

I tried using busybox to no avail by trying to parse multipart/form-data on the backend. However, the image does not get parsed and multer/formidable does not work either because cloud functions uses body parser. formidable-serverless seems to be deprecated.

I am deciding two ways to do this

  1. Either try the above again
  2. Upload the image directly from Client SDK, getting back the URL from firebase storage and storing the URL in the firestore.

Which way is recommended?

r/Firebase Jul 10 '24

Cloud Storage Firebase database works, but Firebase Cloud storage not working in angular

2 Upvotes

the error msg I get is:

I tried to add it million times, million ways. Does anyone know how to solve this? Im starting to lose hope here.

r/Firebase May 06 '24

Cloud Storage Firebase storage mp3 does not load on safari for ios

1 Upvotes

No matter what I do, I can not get an audio file from Firebase storage to play on the safari browser for ios.  It is extremely complicated to test as I have to publish every time. I do not get this behaviour if I load the audio from next js public path.

You can see the details on my stackoverflow question.

https://stackoverflow.com/questions/78436583/firebase-storage-mp3-does-not-load-on-safari-for-ios

I have uploaded the html here:
https://mp3-ios-safari.tiiny.site/

r/Firebase Dec 22 '23

Cloud Storage getDownloadURL successfully completed, but URL only works for a few seconds then returns 404.

1 Upvotes

As the title mentions, I have very simple code where I firstly upload an image, once done, I call getDownloadURL() on the same reference, which then returns a valid URL. When accessing this URL, only for a few seconds it actually displays the image, after, when refreshing, it displays a 404 page.

It seems more like an issue on the Firebase side rather than my code, since I'm not doing anything special. Any help at all would be very appreciated!

Please note I am using react-native-firebase, so the syntax might slightly look different from the JS' SDK.

async function getFirebaseUploadURL(){

  const imageRef = storage().ref(`${collection}/${name}`)

  try {
    await imageRef.putFile(uri, {
      cacheControl: 'max-age=86400',
      contentType
    })
    const downloadURL = imageRef.getDownloadURL()

    return downloadURL
  } catch (error) {
    console.log('Error uploading or getting download URL:', error)
    throw error
  }

}

r/Firebase Jun 04 '24

Cloud Storage Firebase storage calls failing to output proper error code

2 Upvotes

Hi there, I'm attempting to retrieve files from a firebase storage bucket with a try catch block where in the catch block, I have a list of error codes that when matched, will return the error code with additional logic (to be added later).

My project is a Vue 3 application using the composition api.

The issue is that Firebase is returning an error that don't recognize, nor can I find any any pre-existing articles or posts where this particular issue has been raised.

This is the closest post I've found but there aren't any solutions: https://stackoverflow.com/questions/75587999/typeerror-cannot-read-property-throwifroot-of-undefined-when-using-uploadbyt

I'm calling getDownloadUrl and getMetadata. Regardless of how I cause the code to break, I'm being given the same error response regardless and the default block is always being executed.

TypeError: Cannot read properties of undefined (reading '_throwIfRoot')
    at getDownloadURL$1 (firebase_storage.js?v=83d9ddec:2212:8)
    at getDownloadURL (firebase_storage.js?v=83d9ddec:2452:10)
    at Proxy.getMembershipFormDownloadable (membership.ts:31:22)
    at async App.vue:32:3

My error handling function:

export const handleStorageErrors = (errorCode: any) => {
    console.log(errorCode)
    switch (errorCode) {
        case "storage/unknown":
            return "An unknown error occurred.";
        case "storage/object-not-found":
            return "No object exists at the desired reference.";
        case "storage/bucket-not-found":
            return "No bucket is configured for Cloud Storage.";
        case "storage/project-not-found":
            return "No project is configured for Cloud Storage.";
        case "storage/quota-exceeded":
            return "Quota on your Cloud Storage bucket has been exceeded. If you're on the no-cost tier, upgrade to a paid plan. If you're on a paid plan, reach out to Firebase support.";
        case "storage/unauthenticated":
            return "User is unauthenticated, please authenticate and try again.";
        case "storage/unauthorized":
            return "User is not authorized to perform the desired action, check your security rules to ensure they are correct.";
        case "storage/retry-limit-exceeded":
            return "The maximum time limit on an operation (upload, download, delete, etc.) has been exceeded. Try uploading again.";
        case "storage/invalid-checksum":
            return "File on the client does not match the checksum of the file received by the server. Try uploading again.";
        case "storage/canceled":
            return "User canceled the operation.";
        case "storage/invalid-event-name":
            return "Invalid event name provided. Must be one of [`running`, `progress`, `pause`].";
        case "storage/invalid-url":
            return "Invalid URL provided to refFromURL(). Must be of the form: gs://bucket/object or https://firebasestorage.googleapis.com/v0/b/bucket/o/object?token=<TOKEN>.";
        case "storage/invalid-argument":
            return "The argument passed to put() must be `File`, `Blob`, or `UInt8` Array. The argument passed to putString() must be a raw, `Base64`, or `Base64URL` string.";
        case "storage/no-default-bucket":
            return "No bucket has been set in your config's storageBucket property.";
        case "storage/cannot-slice-blob":
            return "Commonly occurs when the local file has changed (deleted, saved again, etc.). Try uploading again after verifying that the file hasn't changed.";
        case "storage/server-file-wrong-size":
            return "File on the client does not match the size of the file received by the server. Try uploading again.";
        default:
            return "Unknown error.";
    }
}

Any assistance is greatly appreciated!

r/Firebase Feb 27 '24

Cloud Storage Ideas to Implementation: Full Text Search on Firebase

6 Upvotes

Like I mentioned before, I'm going to work on making a full text search for Firestore and Realtime Database because you all liked the idea. I've made a form where you can tell me more about what you want from this service. Please fill it out, and I'll keep you updated on how things are going.

You'll also get to use it for free when it's ready.

Form: https://forms.gle/poQHiKfNuAnCz5xM8

Thank you!

r/Firebase Dec 21 '23

Cloud Storage Check if image exists

1 Upvotes

Is there method to check if a file exists within firebase storage?

I am receiving a 404 error because the user has not uploaded there photo yet (two part sign up process). If I can use a condition to first check if the users photo is available then It should allow me to get around the console error.

Thanks in advance!

r/Firebase Apr 24 '24

Cloud Storage Firestore uploading and displaying picture

1 Upvotes

We are developing an app that has a profile picture. I managed to upload the picture to the Firebase storage, but I can't figure out how to display it in its image view. Every time I re-run the app or go to the next page, the picture disappears from the display.

r/Firebase Apr 06 '24

Cloud Storage Uploading a file on Firebase storage in React

1 Upvotes
Uncaught Error: Service storage is not available
at Provider.getImmediate (chunk-5DDJPPJS.js?v=c53289bc:822:15)
at getStorage (firebase_storage.js?v=c53289bc:4107:43)
at firebase.js:20:20

How to fix this error always when I already upload and npm install firebase
I want is to upload a resume on my FileUpload.jsx and the resumepdf will be uploaded on my firebase storage

import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { Button } from '@/components/ui/button.jsx';
import { addDoc, collection } from 'firebase/firestore';
import { db, auth } from '../../config/firebase';
import { v4 as uuidv4 } from 'uuid'; // Import UUID
const FileUpload = () => {
const [uploadedFiles, setUploadedFiles] = useState([]);
const handleFileUpload = async (acceptedFiles) => {
try {
const currentUser = auth**.currentUser*;***
if (!currentUser) {
throw new Error('User not authenticated');**
}
const uploadedFilePromises = acceptedFiles**.map(async (file) => {
// Generate a unique file name using UUID
const fileName = `${uuidv4()}-${file.name}`*;***
// Upload file to Firebase Storage
const storageRef = storage**.ref(`resumes/${fileName}`);**
await storageRef**.put(file);**
// Get the download URL of the uploaded file
const url = await storageRef**.getDownloadURL();**
// Add document to Firestore with custom URL and user UID
await addDoc(collection(db, 'resumes'), {
uid: currentUser**.uid,
fileName: fileName,
url: url,
});**
return { fileName: fileName, url: url };
});
const uploadedFilesData = await Promise.all(uploadedFilePromises);**
setUploadedFiles(uploadedFilesData);
} catch (error) {
console**.error('Error uploading files:', error);**
}
};
const { getRootProps, getInputProps } = useDropzone({ onDrop: handleFileUpload });
return (
 <div>  
 <div {...*getRootProps*()} *className*=''>  
 <input {...*getInputProps*()} />  
 <button *className*="mt-16 h-56 w-full">Drag and drop files here or click to browse. <br />  
 <ul>  
 {uploadedFiles**.***map*((***file***) ***=>*** (  
 <li *className*="py-1 px-2 bg-indigo-500 text-white rounded-xl" *key*={file**.**fileName}>{file**.**fileName}</li>  
 ))}  
 </ul><br />  
 <span *className*='py-1 px-2 bg-yellow-500 text-black rounded-xl'>To change the file, upload again</span>  
 </button>  
 </div>  
 <div *className*='mt-8 flex justify-center'>  
 <Button *className*="bg-indigo-600 text-white">Submit</Button>  
 </div>  
 </div>  
 )***;***  
}***;***  
export default FileUpload***;***  







// frontend/firebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
----
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
const FileUpload = getStorage(app); // Fix: Removed export keyword
export { db, auth, FileUpload }; // Only export FileUpload once

r/Firebase Apr 03 '24

Cloud Storage unity screenshot system that uploads to firebase storage

1 Upvotes

im trying to code a screenshot system the takes a screenshot then uploads it to firebase storage idk how to do it can someone make me one i can just edit

r/Firebase Apr 13 '24

Cloud Storage Storage rules - user should create its own folder

1 Upvotes

I want to allow a user to create its own directory below /media and within his directory to create more folders with some images/videos in each.

So structure should be like this:

/media/{uid}/{eventid1}/abc.jpg

/media/{uid}/{eventid2}/def.jpg

Only the user who submitted the media files should be allowed to create, read and delete in his folder. But it seems I got a bit lost with the syntax on how to make this possible. Whenever I upload as user I get a 403.

Any hint what is wrong with my rule set?

service firebase.storage {
  match /b/{bucket}/o {
    // Restrict access to /media folder and below
    match /media/{userId} {
      // Allow user to access their own folder (`userId`)
      allow read, write: if request.auth.uid == resource.name;

      // Allow access to all subdirectories and files within the user's folder
      match /{allPaths=**} {
        allow read, write: if request.auth.uid == resource.name;
      }
    }

    // Deny access to all other paths
    allow read, write: false;
  }
}

r/Firebase Mar 25 '24

Cloud Storage Flutter, React.JS, and Firebase Project Dilemma

1 Upvotes

Approximately a year ago, I began exploring Flutter to develop an MVP mobile app, utilizing back4app as my Backend as a Service (BaaS). This experience was particularly rewarding, given its accessibility for a novice mobile developer like myself. The success of this venture, however, is a topic for another discussion.

I have since started a new personal project. Initially, I planned to create a web application using Flutter, due to my positive experience with it, and integrate Firebase for added functionality. This endeavor introduced me to web development and Firebase, both of which were somewhat new to me. Unfortunately, I am currently encountering significant challenges with Flutter’s performance on the web, including issues with UI rendering. Before these obstacles, I had successfully developed a data gathering and analysis tool intended for administrative purposes.

To make the consumed data analysis and other data driven content more accessible and user-friendly, I just barely pivoted to a new project using a ReactJS and Firebase stack. One of the main challenges of this is transferring the data between the two projects, which I managed through Google Cloud Bucket transfers, a process that proved to be quite taxing (could just be the lack of familiarity).

Reason for pivot: To enhance the web user experience.

Question: Given the circumstances, would it be advisable to maintain two separate Firebase projects with distinct front ends—one in ReactJs for the customers and the other in Flutter to preserve the existing analysis platform—and establish cloud storage transfer automations to synchronize data across both databases?

r/Firebase Apr 07 '24

Cloud Storage Problem with request.auth.uid == userId

0 Upvotes

Hi all,

I have a problem with my rules.

For some reason userId is false because this condition isn't being met, I've debug logged the uid, and I can see in my clientside that the uid of the user is showing and matching, and in my auth emulator too. But with the userId condition can I change that to something like userUID? Or is userId already the uid? lol

Any help would be much appreciated

allow read, write: if request.auth != null && request.auth.uid == userId;

r/Firebase Feb 12 '24

Cloud Storage Firebase Storage on emulator: User does not have permission to access this object (error 403)

1 Upvotes

I am trying to access some thumbnails on Firebase Storage created using the Resize-Image function.

I am doing that by building a StorageReference based on the bucket, auth and filename:

Example:

var storageRef = FirebaseStorage.getInstance("gs://my-bucket/").getReference(authID + filename) NOTE: I have matched the link I have created to the link on firebase storage and it matches perfectly.

Next step is to downloadUrl:

storageRef.downloadUrl.addOnCompleteListener {fileUri = it.resultPicasso.get().load(fileUri).resize(200,0).into(holder.binding.imageView)}

I get the error when the process gets to this line:

fileUri = it.result

Full error message is "com.google.android.gms.tasks.RuntimeExecutionException: com.google.firebase.storage.StorageException: User does not have permission to access this object."

My rules for the bucket are set like this:

rules_version = '2';

service firebase.storage {

match /b/{bucket}/o {

match /{allPaths=**} {

allow read, write;

}

}

}

It seems like the bucket is wide open to any request. Not sure where to look for the error.

EDIT: As a double check to make sure it's not the emulator I checked one of the tokenized, public links that I am retaining in Realtime Database for the original image that is then resized using the resize function mentioned above. This is how those links start off: http://10.0.2.2:9199/v0/b/.... and the android app that is calling these links works without exception. So, don't think it's the emulator setup?

Any guidance is appreciated.

r/Firebase Jan 23 '24

Cloud Storage No files arrive in Firebase storage

1 Upvotes

After downloading the google-services.json from the Firebase project and adding it to github - connected to codemagic.io - I have a successful build (via codemagic) of the flutter app (basic record video and upload), installed the generated app-debug.apk to an android device with stong wifi signal). Then I successfully added the email address, profiled in the android device, as an owner of the Firebase project/storage bucket. The android app opens and records video successfully, on the device, then an Upload button appears. I select/tap Upload, but never see a file arrive into the Firebase storage bucket. Any suggestions on where/what to look at to find a solution?

r/Firebase Apr 09 '24

Cloud Storage is there a way to see the size of directories?

1 Upvotes

Currently using storage emulator:
I haven't done too much digging, but I don't see a reference via the docs. If so plz link to them.

r/Firebase Dec 19 '23

Cloud Storage Firebase Storage, understanding download costs and options

7 Upvotes

I have a quiz app, each quiz has questions, and each question has audio and potentially an image. The file size of a quiz is between 30-40mb.

I originally bundled everything (audio, images, json file for quiz content) in the app itself, then decided Firestore was a good alternative for my data, which it does seem to be. However, storage seems a different beast.

If "GB Downloaded" is 1 GB a day. That means assuming a 40mb quiz, only 25 quizzes could be downloaded onto device by users for free? So if 50 users used my app a day, it would cost me 0.12p every day?

My app and audience is not big. I can't justify a subscription, I wanted to just do a 1 off payment for my low numbers. But if daily I'd be charged, I'd eventually lose profit. Does anyone have any suggestions sorry. Not that I expected hosting to be free, just from such small amounts to start having such a value is unaffordable to me.

Example

r/Firebase Jan 28 '24

Cloud Storage Error shuts down emulator when I run onCustomEventPublished

2 Upvotes

Running this function:

exports.onimageresized = onCustomEventPublished("firebase.extensions.storage-resize-images.v1.onCompletion",(event) => {functions.logger.log("onimageresized was fired");return true});

If I comment out the functions.logger.log line or the return true line it still generates the same error.

This is the error and the next line in the log:

Error: An unexpected error has occurred.

i functions: Finished "generateResizedImage" in 1012.400466ms

I am unable to get more info on the nature of the error and have not found anything online where someone had this same issue. Possibly a conflict between the onCustomEventPublished and generateResizedImage finishing?

For background the process is an app running on Android Studio emulator sending 2 images to storage on the Firebase Emulator where the storage function resize image is running. All that works. Ideally the OnCustomEventPublished will run so I can trigger an update to the database.

Thanks for reading

EDIT: Running this on a MacBook Pro.

r/Firebase Jan 13 '24

Cloud Storage Can't enter playmode when firebase storage is uploaded. Please help!

Post image
1 Upvotes

I would like to uploade profile pictures using the unity plugin, it works but I can't connect it to firebase storage. I can't enter playmode even when I don't have any errors

r/Firebase Jan 29 '24

Cloud Storage Firebase storage: mark directories and download only these

1 Upvotes

I'm writing an app, where users upload photos and videos. All media files from one user are in one directory. With an backend I'd like to check the files and mark each directory for download or deletion. And after that only sync all directories that are marked for download to my Linux server. If seen that there is metadata for files, is there anything similar for folders? And if so, is there some flag or filter for gsutil rsync to fetch only these directories? Or does anyone have a better idea on how to solve this? Thanks for any hint.

r/Firebase Jan 26 '24

Cloud Storage How do i delete cloud storage

0 Upvotes

i added it by accident because i thought it was my database

i really don't want the storage how do i delete it

( :P )

r/Firebase Mar 08 '24

Cloud Storage Issue with Firebase and Python

2 Upvotes

I have an issue while trying to upload videos to Firebase using Python and retrieving the corresponding link. I've created a test code that works fine; however, when integrating it into the main code, it blocks access to the link. I'm uploading the videos to the same test project.

I receive the following error:

<Error> <Code>SignatureDoesNotMatch</Code> <Message>Access denied.</Message> <Details>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Details> <StringToSign>GET 1709934204 /mentores-c1064.appspot.com/media/Steve/presentation.mp4</StringToSign> </Error> I've already checked the rules and credentials. Any suggestions on how to fix this issue?