Upload files to Firebase Storage using Node.js

前端 未结 6 544
情书的邮戳
情书的邮戳 2020-11-27 14:02

I\'m trying to understand how to upload files in Firebase Storage, using Node.js. My first try was to use the Firebase library:

"use strict";

var f         


        
相关标签:
6条回答
  • 2020-11-27 14:21

    Firebase Admin SDK allows you to directly access your Google Cloud Storage.

    For more detail visit Introduction to the Admin Cloud Storage API

    var admin = require("firebase-admin");
    var serviceAccount = require("path/to/serviceAccountKey.json");
    
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        storageBucket: "<BUCKET_NAME>.appspot.com"
    });
    
    var bucket = admin.storage().bucket();
    
    bucket.upload('Local file to upload, e.g. ./local/path/to/file.txt')
    
    0 讨论(0)
  • 2020-11-27 14:22

    I hope It will useful for you. I uploaded one file from locally and then I added access Token using UUID after that I uploaded into firebase storage.There after I am generating download url. If we hitting that generate url it will automatically downloaded a file.

        const keyFilename="./xxxxx.json"; //replace this with api key file
        const projectId = "xxxx" //replace with your project id
        const bucketName = "xx.xx.appspot.com"; //Add your bucket name
        var mime=require('mime-types');
        const { Storage } = require('@google-cloud/storage');
        const uuidv1 = require('uuid/v1');//this for unique id generation
    
       const gcs = new Storage({
        projectId: projectId,
        keyFilename: './xxxx.json'
         });
        const bucket = gcs.bucket(bucketName);
    
        const filePath = "./sample.odp";
        const remotePath = "/test/sample.odp";
        const fileMime = mime.lookup(filePath);
    
    //we need to pass those parameters for this function
        var upload = (filePath, remoteFile, fileMime) => {
    
          let uuid = uuidv1();
    
          return bucket.upload(filePath, {
                destination: remoteFile,
                uploadType: "media",
                metadata: {
                  contentType: fileMime,
                  metadata: {
                    firebaseStorageDownloadTokens: uuid
                  }
                }
              })
              .then((data) => {
    
                  let file = data[0];
    
                  return Promise.resolve("https://firebasestorage.googleapis.com/v0/b/" + bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media&token=" + uuid);
              });
        }
    //This function is for generation download url    
     upload(filePath, remotePath, fileMime).then( downloadURL => {
            console.log(downloadURL);
    
          });
    
    0 讨论(0)
  • 2020-11-27 14:22

    Note that gcloud is deprecated, use google-cloud instead. You can find SERVICE_ACCOUNT_KEY_FILE_PATH at project settings->Service Accounts.

    var storage = require('@google-cloud/storage');
    
    var gcs = storage({
        projectId: PROJECT_ID,
        keyFilename: SERVICE_ACCOUNT_KEY_FILE_PATH
      });
    
    // Reference an existing bucket.
    var bucket = gcs.bucket(PROJECT_ID + '.appspot.com');
    
    ...
    
    0 讨论(0)
  • 2020-11-27 14:23

    Or you could simply polyfill XmlHttpRequest like so -

    const XMLHttpRequest = require("xhr2");
    global.XMLHttpRequest = XMLHttpRequest
    

    and import

    require('firebase/storage');
    

    That's it. All firebase.storage() methods should now work.

    0 讨论(0)
  • 2020-11-27 14:30

    When using the firebase library on a server you would typically authorize using a service account as this will give you admin access to the Realtime database for instance. You can use the same Service Account's credentials file to authorize gcloud.

    By the way: A Firebase project is essentially also a Google Cloud Platform project, you can access your Firebase project on both https://console.firebase.google.com and https://console.cloud.google.com and https://console.developers.google.com You can see your Project ID on the Firebase Console > Project Settings or in the Cloud Console Dashboard

    When using the gcloud SDK make sure that you use the (already existing) same bucket that Firebase Storage is using. You can find the bucket name in the Firebase web config object or in the Firebase Storage tab. Basically your code should start like this:

    var gcloud = require('gcloud');
    
    var storage = gcloud.storage({
      projectId: '<projectID>',
      keyFilename: 'service-account-credentials.json'
    });
    
    var bucket = storage.bucket('<projectID>.appspot.com');
    
    ...
    
    0 讨论(0)
  • 2020-11-27 14:37

    Firebase Storage is now supported by the admin SDK with NodeJS:

    https://firebase.google.com/docs/reference/admin/node/admin.storage

    // Get the Storage service for the default app
    var defaultStorage = firebaseAdmin.storage();
    var bucket = defaultStorage.bucket('bucketName');
    ...
    
    0 讨论(0)
提交回复
热议问题