如何使用Cloud Functions在Google Cloud Storage的文件夹中下载文件?

时间:2018-08-21 15:57:49

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

我正在使用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控制台的文件夹中。实际上,所有对象都位于存储桶级别,并且仅在名称中包含目录结构。例如,如果您创建一个名为pets的文件夹并将文件cat.jpeg添加到该文件夹​​,则GCP控制台将使该文件看起来像存在于该文件夹中。实际上,没有单独的文件夹实体:该文件仅存在于存储桶中,名称为pets / cat.jpeg。

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

1 个答案:

答案 0 :(得分:0)

通过@James Poag发表评论答案以提高知名度:

另外,也许目录在临时文件夹位置上不存在?也许让tempFilePath = path.join(os.tmpdir(), 'tempkjhgfhjnmbvgh.docx');-詹姆斯·波格8月21日在17:10