简体   繁体   English

将文件从 Firebase 云函数上传到云存储

[英]Uploading files from Firebase Cloud Functions to Cloud Storage

The documentation is too complex for me to understand. 文档太复杂了,我无法理解。 It shows how to download a file from Cloud Storage to Cloud Functions, manipulate the file, and then upload the new file to Cloud Storage.它展示了如何将文件从 Cloud Storage 下载到 Cloud Functions、操作文件,然后将新文件上传到 Cloud Storage。 I just want to see the basic, minimum instructions for uploading a file from Cloud Functions to Cloud Storage.我只想查看将文件从 Cloud Functions 上传到 Cloud Storage 的基本、最低限度的说明。 Why doesn't this work:为什么这不起作用:

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

});

The error message is admin.storage(...).ref is not a function .错误消息是admin.storage(...).ref is not a function I'm guessing that firebase-admin includes Firestore but not Storage?我猜firebase-admin包括 Firestore 但不包括 Storage? Instead of firebase-admin should I use @google-cloud/storage ?我应该使用@google-cloud/storage而不是firebase-admin吗? Why doesn't this work:为什么这不起作用:

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

});

I can't even deploy this code, the error message is我什至无法部署此代码,错误消息是

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

Apparently a npm module dependency is missing?显然缺少 npm 模块依赖项? But the module isn't called clone.js ?但是这个模块不叫clone.js吗? I tried requiring child-process-promise , path , os , and fs ;我尝试要求child-process-promisepathosfs none fixed the missing clone.js error. none 修复了丢失的clone.js错误。

Why does admin.initializeApp();为什么admin.initializeApp(); lack parameters, when in my index.html file I have:缺少参数,当在我的index.html文件中时,我有:

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

Another issue I'm seeing:我看到的另一个问题:

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

In other words, there's something wrong with firebase-admin , or with Node 6.11.2 .换句话说, firebase-adminNode 6.11.2有问题。 Should I use a Node Version Manager to revert to an older version of Node?我应该使用 Node 版本管理器恢复到旧版本的 Node 吗?

  1. Go to https://console.cloud.google.com/iam-admin/iam转到https://console.cloud.google.com/iam-admin/iam
  2. Click the pencil icon next to your App Engine default service account点击App Engine default service account旁边的铅笔图标
  3. + ADD ANOTHER ROLE
  4. Add Cloud Functions Service Agent添加Cloud Functions Service Agent

In my specific use case, I needed to decode a base64 string into a byte array and then use that to save the image.在我的特定用例中,我需要将 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}`)
        })
    }

Then you can call the method like this and chain the calls.然后你可以像这样调用方法并链接调用。

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

Note: You must initialize admin with a service account and specify the default bucket.注意:您必须使用服务帐户初始化 admin 并指定默认存储桶。 If you simply do admin.initializeApp() then your image urls will expire in 10 days.如果您只是执行admin.initializeApp()那么您的图片网址将在 10 天后过期。

Steps to properly use a service account.正确使用服务帐号的步骤。

  1. Go to Service Accounts and generate a private key转到服务帐户并生成私钥
  2. Put the JSON file in your functions folder (next to src and node_modules)将 JSON 文件放在您的函数文件夹中(在 src 和 node_modules 旁边)
  3. Go to Storage and copy the URL not including the "gs://" in the front.转到存储并复制前面不包括“gs://”的 URL。 Use this for the storage bucket url when initializing admin.初始化管理员时,将此用于存储桶 url。
  4. Use your project ID above for the database URL.使用上面的项目 ID 作为数据库 URL。

I uploaded a file from my hard drive to Firebase Cloud Storage via Google Cloud Functions.我通过 Google Cloud Functions 将一个文件从我的硬盘上传到 Firebase Cloud Storage。 First, I found the documentation for Google Cloud Functions bucket.upload .首先,我找到了 Google Cloud Functions bucket.upload文档

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

The first three lines are Cloud Functions boilerplate.前三行是 Cloud Functions 样板。 The next line下一行

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

creates the Cloud Function and sets the trigger.创建云函数并设置触发器。 The next three lines are more Google Cloud boilerplate.接下来的三行是更多的 Google Cloud 样板。

The rest of the code locates the file hello_world.ogg on my computer's hard drive in the functions folder of my project directory and uploads it to the directory Test_Folder and changes the name of the file to hello_world.dog in my Firebase Cloud Storage.其余代码在我的计算机硬盘驱动器上我的项目目录的functions文件夹中找到文件hello_world.ogg并将其上传到目录Test_Folder并将文件的名称更改为我的 Firebase Cloud Storage 中的hello_world.dog This returns a promise, and the next line const file = data[0];这将返回一个承诺,下一行const file = data[0]; is unnecessary unless you want to do something else with the file.除非您想对文件做其他事情,否则是不必要的。

Lastly we return 0;最后我们return 0; . . This line does nothing except prevent the error message除了阻止错误消息外,这一行什么都不做

Function returned undefined, expected Promise or Value

See Introduction to the Admin Cloud Storage API for further details on how to use the Cloud Storage service in Firebase Admin SDK.有关如何在 Firebase Admin SDK 中使用 Cloud Storage 服务的更多详细信息,请参阅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.

Regarding uploading objects, see Cloud Storage Documentation Uploading Objects sample code:关于上传对象,请参见Cloud Storage 文档上传对象示例代码:

 // 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, eg my-bucket'; // const filename = 'Local file to upload, eg ./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}.`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将文件上传到 firebase 存储和云 firebase 时创建 2 个不同的 url - 2 different urls created while uploading files to firebase storage and cloud firebase Firebase 管理员 SDK 具有用于云存储的云功能 - Firebase Admin SDK with Cloud functions for cloud storage Firebase:云函数+存储读取文件 - Firebase: Cloud Functions + Storage Read File 从firebase函数上传数据到firebase存储? - Uploading data from firebase functions to firebase storage? 将文件写入存储的云功能方法? - Cloud Functions methods for writing files to Storage? 与 firebase 云函数中的 firebase firestore 交互 - Interacting with firebase firestore from firebase cloud functions 如何通过Cloud Functions上传文件到Cloud Storage,并使用Firestore控制对Cloud Storage的访问? - How can I upload files to Cloud Storage through Cloud Functions and use Firestore to control access to Cloud Storage? 从 Flutter 中的 Firebase 云存储中删除文件夹 - Deleting a folder from Firebase Cloud Storage in Flutter Firebase 使用云存储触发器上传的用户文件的存储轨道大小 - Firebase Storage track size of uploaded user files with Cloud Storage triggers 为什么 gcloud app deploy 将 0 个文件上传到谷歌云存储? - Why is gcloud app deploy uploading 0 files to google cloud storage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM