使用Node.js将文件上传到Firebase存储

8mmmxcuj  于 2023-03-17  发布在  Node.js
关注(0)|答案(7)|浏览(149)

我正在尝试了解如何使用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模块中,您可以使用gcloud Node.js客户端。
$ npm install --save gcloud
在您的代码中,您可以使用以下命令访问您的存储桶:

var gcloud = require('gcloud')({ ... }); var gcs = gcloud.storage();
var bucket = gcs.bucket('<your-firebase-storage-bucket>');
  • 我们是否可以在没有Google云平台帐户的情况下使用gcloud?如何使用?
  • 如果没有,为什么可以从客户端将文件上传到Firebase Storage?
  • 难道我们不能创建一个从服务器端发出相同请求的库吗?
  • Firebase存储到底是如何与谷歌云平台连接的?为什么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);
});
ocebsuys

ocebsuys1#

当在服务器上使用firebase库时,你通常会授权using a service account,因为这会给予你对实时数据库的管理员访问权限。你可以使用同一个服务帐户的凭证文件来授权gcloud。
顺便说一下:Firebase项目本质上也是Google Cloud Platform项目,您可以在https://console.firebase.google.comhttps://console.cloud.google.comhttps://console.developers.google.com上访问您的Firebase项目您可以在Firebase Console > Project SettingsCloud Console Dashboard上查看您的项目ID
在使用gcloud SDK时,请确保您使用的存储桶与Firebase Storage使用的存储桶(已经存在)相同。您可以在Firebase web config对象或Firebase Storage选项卡中找到存储桶名称。基本上,您的代码应该如下所示:

var gcloud = require('gcloud');

var storage = gcloud.storage({
  projectId: '<projectID>',
  keyFilename: 'service-account-credentials.json'
});

var bucket = storage.bucket('<projectID>.appspot.com');

...
idv4meu8

idv4meu82#

Firebase存储现在受NodeJS的管理SDK支持:
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');
...
gg58donl

gg58donl3#

Firebase Admin SDK允许您直接访问Google云存储。
有关详细信息,请访问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')
j9per5c4

j9per5c44#

我希望它会对你有用。我上传了一个文件从本地,然后我添加了访问令牌使用UUID后,我上传到firebase存储。有后,我生成下载网址。如果我们点击生成网址,它会自动下载一个文件。

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

      });
wydwbb8l

wydwbb8l5#

注意gcloud已经过时了,请使用google-cloud。你可以在项目设置-〉服务帐户中找到SERVICE_ACCOUNT_KEY_FILE_PATH。

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

...
rlcwz9us

rlcwz9us6#

或者你可以像这样简单地用聚合物填充XmlHttpRequest-

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

并导入

require('firebase/storage');

就是这样,所有firebase.storage()方法现在都应该可以工作了。

wnavrhmk

wnavrhmk7#

我已经实现了将文件上传到firebase存储器的API:

const fs = require('firebase-admin');
const app = require('express')();
const serviceAccount = require('./serviceAccountKey_DEV.json');

fs.initializeApp({
    credential: fs.credential.cert(serviceAccount),
    storageBucket: `${serviceAccount.project_id}.appspot.com`
});

// Upload the file on firebase storage
app.get("/upload-on-firebase", async (req, res, next) => {
    var bucket = fs.storage().bucket();
    const result = await bucket.upload('data.json');
    console.log('result :', result);
    return res.send(result);
});

调用API上传:

curl --location --request GET 'http://localhost:3000/upload-on-firebase'

答复:

[
    {
        "_events": {},
        "_eventsCount": 0,
        "metadata": {
            "kind": "storage#object",
            "id": "project_id.appspot.com/data.json/1678222222",
            "selfLink": "https://www.googleapis.com/storage/v1/b/project_id.appspot.com/o/data.json",
            "mediaLink": "https://storage.googleapis.com/download/storage/v1/b/project_id.appspot.com/o/data.json",
            "name": "data.json",
            "bucket": "project_id.appspot.com",
            "generation": "16787922222222",
            "metageneration": "1",
            "contentType": "application/json",
            "storageClass": "STANDARD",
            ....
            ....
            ....
        },
        "baseUrl": "/o",
    }
]

相关问题