我在尝试了解如何使用Node.js在Firebase存储中上传文件。我的第一次尝试是使用火力地堡库:使用Node.js将文件上传到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 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>');
能我们使用
gcloud
而不在Google云端平台上拥有帐户?怎么样?如果没有,那么如何从客户端上传文件到Firebase存储是可能的?
难道我们不能仅仅创建一个从服务器端发出相同请求的库吗?
Firebase存储如何与Google云端平台连接?为什么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);
});
这是真正有用的,不过,问题的根源仍然存在:用我不能上传东西'gcloud'(例如,创建一个存储桶),因为根据[这个答案](http://stackoverflow.com/a/23136508/1420197),我没有启用计费。同样,为什么通过'gcloud'访问存储需要计费,而通过客户端的Firebase访问存储不会呢?谢谢! –
我在我的问题中添加了另一个片段。 –
看来你可能需要启用计费这是真的。我会在内部向团队报告。我们一直在讨论是否应该为存储创建Firebase特定的Server SDK,现在的共识是“否”。对于结算问题:作为解决方法,您可以启用结算功能,并设置零美元限额的预算,以避免收取任何费用。 API本身应该可以自由使用,并且Firebase Storage使用的存储桶具有免费配额,因此应该可以正常工作。 – Nivco