Firebase 函数从存储中获取文件

标签 firebase google-cloud-functions

我必须向 API 发送文件,因此我必须使用 fs.readFileSync() .将图片上传到存储后,我正在调用我的函数来执行 API 调用。但是我无法从存储中获取文件。这是代码的一部分,它在结果中总是为空。我也试过 .getFiles()没有参数,然后我得到了所有文件,但我不想通过迭代过滤它们。

    exports.stripe_uploadIDs = functions.https //.region("europe-west1")
  .onCall((data, context) => {
    const authID = context.auth.uid;
    console.log("request is authentificated? :" + authID);

    if (!authID) {
      throw new functions.https.HttpsError("not authorized", "not authorized");
    }

    let accountID;
    let result_fileUpload;
    let tempFile = path.join(os.tmpdir(), "id_front.jpg");

    const options_id_front_jpeg = {
      prefix: "/user/" + authID + "/id_front.jpg"
    };

    const storageRef = admin
      .storage()
      .bucket()
      .getFiles(options_id_front)
      .then(results => {
        console.log("JPG" + JSON.stringify(results));
        // need to write this file to tempFile
        return results;
      });

    const paymentRef = storageRef.then(() => {
      return admin
        .database()
        .ref("Payment/" + authID)
        .child("accountID")
        .once("value");
    });

    const setAccountID = paymentRef.then(snap => {
      accountID = snap.val();
      return accountID;
    });

    const fileUpload = setAccountID.then(() => {
      return Stripe.fileUploads.create(
        {
          purpose: "identity_document",
          file: {
            data: tempFile,  // Documentation says I should use fs.readFileSync("filepath")
            name: "id_front.jpg",
            type: "application/octet-stream"
          }
        },
        { stripe_account: accountID }
      );
    });

    const fileResult = fileUpload.then(result => {
      result_fileUpload = result;
      console.log(JSON.stringify(result_fileUpload));
      return result_fileUpload;
    });

    return fileResult;
  });

结果是:
JPG[[]]

最佳答案

您需要将文件从存储桶下载到本地函数上下文环境。
在您的 Firebase 函数开始执行后,您可以调用以下代码:
以下或多或少应该可以工作,只需根据您的需要进行调整。在你内心呼唤这个 .onCall上下文,你明白了

import admin from 'firebase-admin';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';

admin.initializeApp();
const { log } = console;

async function tempFile(fileBucket: string, filePath: string) {

  const bucket = admin.storage().bucket(fileBucket);
  const fileName = 'MyFile.ext';
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const metadata = {
    contentType: 'DONT_FORGET_CONTEN_TYPE'
  };

  // Donwload the file to a local temp file
  // Do whatever you need with it
  await bucket.file(filePath).download({ destination: tempFilePath });
  log('File downloaded to', tempFilePath);

  // After you done and if you need to upload the modified file back to your
  // bucket then uploaded
  // This is optional
  await bucket.upload(tempFilePath, {
    destination: filePath,
    metadata: metadata
  });

  //free up disk space by realseasing the file.
  // Otherwise you might be charged extra for keeping memory space
  return fs.unlinkSync(tempFilePath);
}

关于Firebase 函数从存储中获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131645/

相关文章:

android - 来自图像 flutter firebase 的文本识别

javascript - 如何在谷歌云功能中从快照创建磁盘 - Node js

Firebase 云函数 : is `createId()` available on the server side?

typescript - node_modules/firebase-functions/lib/function-configuration.d.ts :4:64 - error TS1005: ']' expected

android - window.FirebasePlugin.verifyPhoneNumber 函数响应无法使用

java - 如何从firebase :获取数据

Firebase 托管 SPA 的 : How to prevent caching for the index. html

firebase - 如何在 imagemagick 的谷歌云功能中安装自定义字体

javascript - 如果javascript中出现循环,如何处理firebase ref?

firebase - 部署 firebase 云函数时排除某个函数