Home > Mobile >  Firebase Storage TypeError: file.getBlob is not a function
Firebase Storage TypeError: file.getBlob is not a function

Time:05-31

In my app I would like to download files (.pdf and .xls) from Firebase storage.

I can generate a download link using ref.getDownloadURL(), but that link causes the browser to open a new tab before downloading or opening the target file.

In order to avoid this behavior, I can download the the file in javascript using res = await fetch([the download URL]) and then await res.blob()

THIS WORKS FINE:

 const res = await fetch([downloadURL]);
 const blob = await res.blob();     
 const url = URL.createObjectURL(blob);
 const anchor = document.createElement("a");
 anchor.href = url;
 anchor.download = [file_name];  // e.g. my_file.xls
 anchor.click();

However, the documentation suggests that I can download the blob directly via the SDK using getBlob()

I have tried to download a list of the files in my storage bucket and to loop over these to get the blob as follows:

const storageRef = storage.ref().child("my_files");      
const list = await storageRef.listAll();   
const blob_array = await Promise.all(
  list.items       
    .map(async (file) => {
      const blob= await file.getBlob();
      return {
        name: file.name,
        blob: blob,
       };
     })
   );

however, I get an error:

TypeError: file.getBlob is not a function

The documentation for getBlob() states:

To use this functionality, you have to whitelist your app's origin in your Cloud Storage bucket. See also https://cloud.google.com/storage/docs/configuring-cors

In order to test this, I have followed the referenced documentation and, using gsutil, I have set the CORS policy for my storage bucket as follows:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

I thought that this would have the effect of 'whitelisting' my apps origin (per the getBlob() documentation), but instead I still get an error as follows:

TypeError: file.getBlob is not a function

How can I enable this getBlob() functionality?

CodePudding user response:

The problem is exactly that stated by the error - you're trying to call getBlob on an object that doesn't have that method.

Firstly, take a look at the documentation for downloading files. It states that since SDK version 9.5 there is a global getBlob function. You're not using a new enough version of the SDK to get that function. You're using the old version 8, and Reference objects don't have a getBlob method (scan the API documentation v8 for Reference and you just won't see it).

If you want to use getBlob, you'll have to upgrade to the v9 SDK and rewrite all your Firebase code to conform to the new APIs. Then you will be able to use the new getBlob.

  • Related