【问题标题】:Google Cloud Functions bucket.upload()谷歌云函数 bucket.upload()
【发布时间】:2018-10-02 07:44:28
【问题描述】:

我正在尝试使用由 firebase 写入触发的 google 功能将 pdf 文件从远程网站存档到 Google Cloud Storage。

下面的代码有效。但是,此函数将远程文件复制到存储桶根目录。

我想将 pdf 复制到存储桶的 pth:library-xxxx.appspot.com/Orgs/${params.ukey}

如何做到这一点?

exports.copyFiles = functions.database.ref('Orgs/{orgkey}/resources/{restypekey}/{ukey}/linkDesc/en').onWrite(event => {
    const snapshot = event.data;
    const params = event.params;
    const filetocopy = snapshot.val();
    if (validFileType(filetocopy)) {
        const pth = 'Orgs/' + params.orgkey;

        const bucket = gcs.bucket('library-xxxx.appspot.com')
        return bucket.upload(filetocopy)
            .then(res => {
            console.log('res',res);
            }).catch(err => {
            console.log('err', err);
        });
    }
});

【问题讨论】:

    标签: node.js firebase google-cloud-platform google-cloud-functions google-cloud-storage


    【解决方案1】:

    首先让我简要解释一下 GCS 文件系统的工作原理:正如 documentation of Google Cloud Storage 中所解释的,GCS 是一个平面命名空间,其中不存在目录的概念。如果你有像gs://my-bucket/folder/file.txt这样的对象,这意味着在gs://my-bucket的根目录中存储了一个名为folder/file.txt的对象,即对象名称包含/字符。确实,Console 中的 GCS UI 和 gsutil CLI 工具造成了具有分层文件结构的错觉,但这只是为了让用户更加清晰,即使那些目录不存在,一切都是存储在“平面”名称空间中。

    话虽如此,如the reference for the storage.bucket.upload() method 中所述,您可以指定一个包含destination 字段的options 参数,您可以在其中指定一个带有完整文件名的字符串

    仅作为示例(注意两个函数之间的options 参数差异):

    var bucket = storage.bucket('my-sample-bucket');
    
    var options = {
      destination: 'somewhere/here.txt'
    };
    
    bucket.upload('sample.txt', function(err, file) {
        console.log("Created object gs://my-sample-bucket/sample.txt");
    });
    
    bucket.upload('sample.txt', options, function(err, file) {
        console.log("Created object gs://my-sample-bucket/somewhere/here.txt");
    });
    

    因此,在您的情况下,您可以构建一个包含您要使用的完整名称的字符串(还包含您想到的“目录”结构)。

    【讨论】:

    • 我很高兴能帮上忙!如果答案对您有用,请考虑accepting and/or upvoting我的答案,以便社区看到它解决了您的问题。谢谢!
    【解决方案2】:

    filepath -->本机文件存放路径

     await bucket.upload(filepath, {
          public: true,
          gzip: true,
          metadata: {
            cacheControl: "public, max-age=31536000",
          },
        });
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 2018-12-07
      • 2021-01-22
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 2020-11-21
      相关资源
      最近更新 更多