Ion*_*zău 31 javascript node.js firebase gcloud firebase-storage
我正在尝试使用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);
});
Run Code Online (Sandbox Code Playgroud)
但事实证明,Firebase无法从服务器端上传文件,因为它在文档中明确指出:
Firebase存储不包含在服务器端Firebase npm模块中.相反,您可以使用gcloud Node.js客户端.
$ npm install --save gcloud在您的代码中,您可以使用以下方式访问存储桶:
Run Code Online (Sandbox Code Playgroud)var gcloud = require('gcloud')({ ... }); var gcs = gcloud.storage(); var bucket = gcs.bucket('<your-firebase-storage-bucket>');
我们可以在gcloud没有Google Cloud Platform帐户的情况下使用吗?怎么样?
如果没有,为什么可以从客户端上传文件到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);
});
Run Code Online (Sandbox Code Playgroud)
Nic*_*ier 18
在服务器上使用firebase库时,通常会使用服务帐户进行授权,因为这将为您提供对Realtime数据库的管理访问权限.您可以使用相同的服务帐户的凭据文件来授权gcloud.
顺便说一句:Firebase项目本质上也是一个Google Cloud Platform项目,您可以通过https://console.firebase.google.com和https://console.cloud.google.com以及https访问您的Firebase项目: //console.developers.google.com 您可以在Firebase控制台>项目设置或云控制台信息中心中查看您的项目ID
使用gcloud SDK时,请确保使用Firebase存储使用的(现有)相同存储桶.您可以在Firebase网络config对象或Firebase存储选项卡中找到存储桶名称.基本上你的代码应该像这样开始:
var gcloud = require('gcloud');
var storage = gcloud.storage({
projectId: '<projectID>',
keyFilename: 'service-account-credentials.json'
});
var bucket = storage.bucket('<projectID>.appspot.com');
...
Run Code Online (Sandbox Code Playgroud)
Lau*_*ent 15
带有NodeJS的admin SDK现在支持Firebase存储:
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');
...
Run Code Online (Sandbox Code Playgroud)
我希望它对你有用。我从本地上传了一个文件,然后我使用 UUID 添加了访问令牌,之后我上传到了 firebase 存储。在我生成下载 url 之后。如果我们点击该生成网址,它将自动下载一个文件。
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);
});
Run Code Online (Sandbox Code Playgroud)
小智 5
Firebase Admin SDK允许您直接访问Google云端存储。
有关更多详细信息,请访问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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26028 次 |
| 最近记录: |