我试图了解如何使用 Node.js 在 Firebase 存储中上传文件。我的第一次尝试是使用 Firebase 库:
"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 无法从服务器端上传文件,正如文档中明确指出的那样:
Firebase 存储不包含在服务器端 Firebase npm module中。相反,您可以使用 gcloud Node.js 客户端。
$ npm install --save gcloud
在您的代码中,您可以使用以下方式访问您的存储桶:
var gcloud = require('gcloud')({ ... }); var gcs = gcloud.storage(); var bucket = gcs.bucket('<your-firebase-storage-bucket>');
我们可以在
gcloud
没有 Google Cloud Platform 帐户的情况下使用吗?如何?如果没有,为什么可以从客户端将文件上传到 Firebase 存储?
我们不能创建一个从服务器端发出相同请求的库吗?
Firebase Storage 是如何与 Google Cloud Platform 连接的?为什么 Firebase 只允许我们从客户端上传图片?
我的第二次尝试是使用该gcloud
库,如文档中所述:
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);
});