首页 > 解决方案 > 如何将文件上传到 Google Cloud Storage Bucket 子目录

问题描述

我想使用 Go 将文件上传到谷歌云存储桶子目录。我找到的唯一参考代码是link

wc := client.Bucket(bucket).Object(object).NewWriter(ctx)

object是您的文件名的字符串,但不允许使用文件路径。当我使用像/path/filename. 它仅在您使用filename.

连接:无法分配请求的地址

以前我使用 node.js,它工作正常。

await bucket.upload(filePath, { destination: `path/filename`, resumable:false });

我怎样才能用 Go 实现呢?

标签: gogoogle-cloud-storage

解决方案


继续 Node 示例,存储桶始终是顶级存储桶名称。

子目录成为“文件”的一部分。GCP 将子目录 + 文件视为一个对象。是的,这是违反直觉的。


const bucketName = 'top-level-bucket-name';
const subBucketName = 'sub_level/another_sub_level/';
// Cloud Function uses /tmp not ./tmp
const directory = './tmp'; 
const fileName = 'foo.txt';

storage.bucket(bucketName).upload(`${directory}/${fileName}`, { destination: subBucketName + fileName});

我遇到了子目录中的连字符不起作用的问题,这就是为什么有下划线。


推荐阅读