使用 Node.js 将文件上传到 Firebase 存储 [英] Upload files to Firebase Storage using Node.js

查看:25
本文介绍了使用 Node.js 将文件上传到 Firebase 存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用 Node.js 在 Firebase 存储中上传文件.我的第一次尝试是使用 Firebase 库:

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 firebase = require('firebase');

var config = {
    apiKey: "AIz...kBY",
    authDomain: "em....firebaseapp.com",
    databaseURL: "https://em....firebaseio.com",
    storageBucket: "em....appspot.com",
    messagingSenderId: "95...6"
};

firebase.initializeApp(config);

// Error: firebase.storage is undefined, so not a function
var storageRef = firebase.storage().ref();

var uploadTask = storageRef.child('images/octofez.png').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
    ...
}, function(error) {
    console.error("Something nasty happened", error);
}, function() {
  var downloadURL = uploadTask.snapshot.downloadURL;
  console.log("Done. Enjoy.", downloadURL);
});

但事实证明 Firebase 无法从服务器端上传文件,正如文档中明确指出的那样:

But it turns out that Firebase cannot upload files from the server side, as it clearly states in the docs:

Firebase 存储不包含在服务器端 Firebase npm 模块中.相反,您可以使用 gcloud Node.js 客户端.

Firebase Storage is not included in the server side Firebase npm module. Instead, you can use the gcloud Node.js client.

$ npm install --save gcloud

在您的代码中,您可以使用以下方式访问您的存储分区:

In your code, you can access your Storage bucket using:

var gcloud = require('gcloud')({ ... }); var gcs = gcloud.storage();
var bucket = gcs.bucket('<your-firebase-storage-bucket>');

  • 我们可以在没有 Google Cloud Platform 帐户的情况下使用 gcloud 吗?怎么样?

    如果不能,那怎么可以从客户端上传文件到 Firebase Storage?

    If not, how come that uploading files to Firebase Storage from the client side is possible?

    我们不能创建一个从服务器端发出相同请求的库吗?

    Can't we just create a library that makes the same requests from the server side?

    Firebase Storage 是如何与 Google Cloud Platform 连接的?为什么 Firebase 只允许我们从客户端上传图片?

    How is Firebase Storage connected with Google Cloud Platform at all? Why Firebase allows us to upload images only from the client side?

    我的第二次尝试是使用 gcloud 库,如文档中所述:

    My second try was to use the gcloud library, like mentioned in the docs:

    var gcloud = require("gcloud");
    
    // The following environment variables are set by app.yaml when running on GAE,
    // but will need to be manually set when running locally.
    // The storage client is used to communicate with Google Cloud Storage
    var storage = gcloud.storage({
      projectId: "em...",
      keyFilename: 'auth.json'
    });
    
    storage.createBucket('octocats', function(err, bucket) {
    
        // Error: 403, accountDisabled
        // The account for the specified project has been disabled.
    
        // Create a new blob in the bucket and upload the file data.
        var blob = bucket.file("octofez.png");
        var blobStream = blob.createWriteStream();
    
        blobStream.on('error', function (err) {
            console.error(err);
        });
    
        blobStream.on('finish', function () {
            var publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`;
            console.log(publicUrl);
        });
    
        fs.createReadStream("octofez.png").pipe(blobStream);
    });
    

    推荐答案

    在服务器上使用 firebase 库时,您通常会授权 使用服务帐户,因为这将授予您对实时数据库的管理员访问权限.您可以使用同一个服务帐号的凭据文件来授权 gcloud.

    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.

    顺便说一句:Firebase 项目本质上也是一个 Google Cloud Platform 项目,您可以在 上访问您的 Firebase 项目https://console.firebase.google.comhttps://console.cloud.google.comhttps://console.developers.google.com您可以在 Firebase 控制台 > 项目设置 上查看您的项目 ID,或者在 Cloud Console 信息中心

    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

    在使用 gcloud SDK 时,请确保您使用 Firebase Storage 正在使用的(已经存在的)相同存储桶.您可以在 Firebase Web config 对象或 Firebase 存储选项卡中找到存储桶名称.基本上你的代码应该像这样开始:

    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');
    
    ...
    

    这篇关于使用 Node.js 将文件上传到 Firebase 存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆