将文件从Firebase云功能上传到云存储

j0pj023g  于 2023-02-05  发布在  其他
关注(0)|答案(4)|浏览(123)

documentation太复杂了,我看不懂。它展示了如何从云存储下载文件到云功能,操作文件,然后上传新文件到云存储。我只想看看从云功能上传文件到云存储的基本说明。为什么这不起作用:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.storage = functions.firestore.document('Test_Value').onUpdate((change, context) => {

  var metadata = {
    contentType: 'text',
  };

  admin.storage().ref().put( {'test': 'test'}, metadata)
  .then(function() {
    console.log("Document written.");
  })
  .catch(function(error) {
    console.error(error);
  })

});

错误消息是admin.storage(...).ref is not a function。我猜firebase-admin包括Firestore但不包括Storage?我应该使用@google-cloud/storage来代替firebase-admin吗?为什么这样做不起作用:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const {Storage} = require('@google-cloud/storage')();
const storage = new Storage();

admin.initializeApp();

exports.storage = functions.firestore.document('Test_Value').onUpdate((change, context) => {

  storage.bucket().upload( {'test': 'test'} , {
    metadata: {
      contentType: 'text'
    }
  })

});

我甚至无法部署此代码,错误消息是

Error parsing triggers: Cannot find module './clone.js'

显然缺少了一个npm模块依赖项,但是这个模块不是clone.js,我试着要求child-process-promisepathosfs;没有修复丢失的clone.js错误。
为什么admin.initializeApp();缺少参数,当我在index.html文件中有:

firebase.initializeApp({
    apiKey: 'swordfish',
    authDomain: 'myapp.firebaseapp.com',
    databaseURL: "https://myapp.firebaseio.com",
    projectId: 'myapp',
    storageBucket: "myapp.appspot.com"
  });

我看到的另一个问题是:

npm list -g --depth=0       

/Users/TDK/.nvm/versions/node/v6.11.2/lib
├── child_process@1.0.2
├── UNMET PEER DEPENDENCY  error: ENOENT: no such file or directory, open '/Users/TDK/.nvm/versions/node/v6.11.2/lib/node_modules/firebase-admin/package.json
├── firebase-functions@2.1.0
├── firebase-tools@6.0.1
├── firestore-backup-restore@1.3.1
├── fs@0.0.2
├── npm@6.4.1
├── npm-check@5.9.0
├── protractor@5.4.1
├── request@2.88.0
└── watson-developer-cloud@3.13.0

换句话说,firebase-adminNode 6.11.2有问题,我应该使用节点版本管理器恢复到旧版本的节点吗?

2lpgd968

2lpgd9681#

1.转到https://console.cloud.google.com/iam-admin/iam
1.单击App Engine default service account旁边的铅笔图标

  1. + ADD ANOTHER ROLE
    1.添加Cloud Functions Service Agent
    在我的特定用例中,我需要将base64字符串解码为字节数组,然后使用该数组保存图像。
var serviceAccount = require("./../serviceAccountKey.json");

    import * as functions from 'firebase-functions';
    import * as admin from 'firebase-admin';    

    admin.initializeApp({
        projectId: serviceAccount.project_id, 
        credential: admin.credential.cert(serviceAccount),
        databaseURL: "https://your_project_id_here.firebaseio.com", //update this
        storageBucket: "your_bucket_name_here.appspot.com" //update this
      });

    function uploadProfileImage(imageBytes64Str: string): Promise<any> {

        const bucket = admin.storage().bucket()
        const imageBuffer = Buffer.from(imageBytes64Str, 'base64')
        const imageByteArray = new Uint8Array(imageBuffer);
        const file = bucket.file(`images/profile_photo.png`);
        const options = { resumable: false, metadata: { contentType: "image/jpg" } }

        //options may not be necessary
        return file.save(imageByteArray, options)
        .then(stuff => {
            return file.getSignedUrl({
                action: 'read',
                expires: '03-09-2500'
              })
        })
        .then(urls => {
            const url = urls[0];
            console.log(`Image url = ${url}`)
            return url
        })
        .catch(err => {
            console.log(`Unable to upload image ${err}`)
        })
    }

然后可以像这样调用该方法并将调用链接起来。

uploadProfileImage(image_bytes_here)
    .then(url => {
        //Do stuff with the url here        
    })

注意:您必须使用服务帐户初始化管理员,并指定默认存储桶。如果您只是执行admin.initializeApp(),则映像URL将在10天后过期。
正确使用服务帐户的步骤。
1.转到Service Accounts并生成私钥
1.将JSON文件放在函数文件夹中(在src和node_modules旁边)
1.转到Storage并复制不包括前面的"gs://"的URL。初始化管理时将其用作存储桶URL。
1.使用上面的项目ID作为数据库URL。

cbeh67ev

cbeh67ev2#

有关如何在Firebase Admin SDK中使用云存储服务的更多详细信息,请参见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' is an object defined in the @google-cloud/storage library.
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/storage/latest/storage/bucket
// for more details.

有关上载对象,请参阅云存储文档上载对象示例代码:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

// Uploads a local file to the bucket
await storage.bucket(bucketName).upload(filename, {
  // Support for HTTP requests made with `Accept-Encoding: gzip`
  gzip: true,
  metadata: {
    // Enable long-lived HTTP caching headers
    // Use only if the contents of the file will never change
    // (If the contents will change, use cacheControl: 'no-cache')
    cacheControl: 'public, max-age=31536000',
  },
});

console.log(`${filename} uploaded to ${bucketName}.`);
a7qyws3x

a7qyws3x3#

我通过Google Cloud Functions从硬盘上传了一个文件到Firebase Cloud Storage。首先,我找到了Google Cloud Functions的documentation bucketiderupload。

const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.Storage = functions.firestore.document('Storage_Value').onUpdate((change, context) => {
    
      const {Storage} = require('@google-cloud/storage');
      const storage = new Storage();
      const bucket = storage.bucket('myapp.appspot.com');
    
      const options = {
        destination: 'Test_Folder/hello_world.dog'
      };
    
      bucket.upload('hello_world.ogg', options).then(function(data) {
        const file = data[0];
      });
    
      return 0;
    });

前三行是云函数样板。

exports.Storage = functions.firestore.document('Storage_Value').onUpdate((change, context) => {

创建云函数并设置触发器。接下来的三行更像是谷歌云的样板文件。
剩下的代码在我的项目目录的functions文件夹中找到我的计算机硬盘上的文件hello_world.ogg,并将其上传到目录Test_Folder,在我的Firebase云存储中将文件名更改为hello_world.dog,这将返回一个承诺,除非您想对该文件执行其他操作,否则下一行const file = data[0];是不必要的。
最后,我们使用return 0;。这一行除了防止错误消息外什么也不做

Function returned undefined, expected Promise or Value
vawmfj5a

vawmfj5a4#

if (req.rawBody) {
    busboy.end(req.rawBody);
}
else {
    req.pipe(busboy);
}

如本期所述:https://github.com/GoogleCloudPlatform/cloud-functions-emulator/issues/161#issuecomment-376563784

相关问题