【问题标题】:How can I download file inside a folder in Google Cloud Storage using Cloud Functions?如何使用 Cloud Functions 在 Google Cloud Storage 的文件夹中下载文件?
【发布时间】:2018-08-21 15:57:48
【问题描述】:

我正在使用 https 触发的 Google Cloud Function,它应该从 Google Cloud Storage 下载文件(然后将其与来自 req.body 的数据结合起来)。尽管只要下载的文件位于根目录中,它似乎就可以工作,但当我将其放置在文件夹中时,我在访问同一文件时遇到了问题。文件路径为documents/someTemplate.docx

'use strict';
const functions = require('firebase-functions');
const path = require('path');
const os = require("os");
const fs = require('fs');
const gcconfig = {
  projectId: "MYPROJECTNAME",
  keyFilename: "KEYNAME.json"
};
const Storage = require('@google-cloud/storage')(gcconfig)
const bucketPath = 'MYPROJECTNAME.appspot.com'
const bucket = Storage.bucket(bucketPath);

exports.getFileFromStorage = functions.https.onRequest((req, res) => {
      let fileName = 'documents/someTemplate.docx'
      let tempFilePath = path.join(os.tmpdir(), fileName);

      return bucket.file(fileName)
      .download({
          destination: tempFilePath,
        })
        .then(() => {
          console.log(fileName + ' downloaded locally to', tempFilePath);
          let content = fs.readFileSync(tempFilePath, 'binary');

          // do stuff with the file and data from req.body

          return
        })
        .catch(err => {
          res.status(500).json({
            error: err
          });
        });
})

我不明白的是,当我将文件移动到根目录并使用文件名someTemplate.docx 时,代码就可以工作了。

Google's documentation 声明

添加到文件夹的对象似乎驻留在 GCP Console 的文件夹中。实际上,所有对象都存在于存储桶级别,并且只是在其名称中包含目录结构。例如,如果您创建一个名为 pets 的文件夹并将文件 cat.jpeg 添加到该文件夹​​,GCP Console 会使该文件看起来存在于该文件夹中。实际上,没有单独的文件夹实体:文件只是存在于存储桶中,名称为 pets/cat.jpeg。

这似乎是正确的,因为在元数据中文件名确实是documents/someTemplate.docx。因此我不明白为什么上面的代码不起作用。

【问题讨论】:

  • 究竟是什么不起作用?有错误信息吗?
  • 使用firebase serve --only functions在本地运行,这样你就可以得到控制台错误(更快)。
  • 另外,临时文件夹位置上可能不存在该目录?也许试试let tempFilePath = path.join(os.tmpdir(), 'tempkjhgfhjnmbvgh.docx');
  • @JamesPoag 谢谢,这就是问题所在,我没有意识到它不会自动创建文件夹。奇怪的是,即使我一直使用firebase serve,我也从未收到错误消息。它会告诉我,例如 Execution took 16 ms, user function completed successfully 但既不运行 then 也不运行 catch 部分。
  • 我想很多人使用tmp节点模块:npm install tmp

标签: google-cloud-platform google-cloud-storage google-cloud-functions


【解决方案1】:

发布来自@James Poag 的评论答案以提高知名度:

另外,临时文件夹位置上可能不存在该目录?也许试试让tempFilePath = path.join(os.tmpdir(), 'tempkjhgfhjnmbvgh.docx'); – James Poag 8 月 21 日 17:10

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 2018-04-22
    • 1970-01-01
    • 2020-02-16
    • 2019-09-27
    • 1970-01-01
    • 2014-10-13
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多