使用 NodeJS 从 GCP 存储下载对象

Dio*_*iar 3 node.js google-cloud-storage google-cloud-platform google-iam

我正在使用@google-cloud/storage从节点应用程序访问 Google Cloud Storage 存储桶内的对象,但我无法使其工作。

我已在 GCP 控制台上创建了一个服务帐户,并为其分配了存储管理员角色,但当我尝试获取文件时,我收到以下消息:

service-account-user@my-project-5411148.iam.gserviceaccount.com 没有 storage.objects.get 访问 my-bucket-45826813215/some-object 的权限。

查看存储桶的权限选项卡,我可以看到服务帐户与继承的注释一起列出,并且我没有为对象设置任何特定权限。

我的代码如下所示:

const { Storage } = require('@google-cloud/storage');
const config = require('./config');
const storage = new Storage({ 'keyFilename': config.configFullPath('gcloud') });

const privateBucket = storage.bucket('my-bucket-45826813215'); 

let objectDownload = async (filename) => {
    let file = privateBucket.file(filename);
    let result = await file.download();
    return result;
}

objectDownload('some-object')
    .then(() => {
        console.log('Done');
    })
    .catch((err) => {
        console.log(err.message);
    });
Run Code Online (Sandbox Code Playgroud)

关于我做错了什么有什么想法吗?

San*_*tel 11

我能够下载带有Storage Admin Role. 以下是我遵循的过程

1. 创建项目 在此输入图像描述

2. 进入IAM并选择服务账户

在此输入图像描述

3. 选择创建服务帐户 在此输入图像描述

4.选择服务帐户的角色 在此输入图像描述

5. 创建密钥

在此输入图像描述 在此输入图像描述 在此输入图像描述

下面是工作代码:

const path = require('path');
const {Storage} = require('@google-cloud/storage');


async function test() {

const serviceKey = path.join(__dirname, './keys.json')


const storageConf = {keyFilename:serviceKey}

const storage = new Storage(storageConf)

const downlaodOptions = {
      destination: __dirname+'/test.jpg'
    };

    try {
    let res =await storage
      .bucket('storage1232020')
      .file('test.jpg')
      .download(downlaodOptions); 
   }
   catch(err){
    console.log(err)
   }

}

test()
Run Code Online (Sandbox Code Playgroud)

注意:确保

  1. 在项目下创建服务帐户和存储桶。例如,我为项目storage-dem01232020创建了一个存储桶和服务帐户

  2. 您正在正确地将密钥传递给代码

下载文件的方式

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
// Download a file into memory. The contents will be available as the
second
// argument in the demonstration below, `contents`.
//-
file.download(function(err, contents) {});

//-
// Download a file to a local destination.
//-
file.download({
  destination: '/Users/me/Desktop/file-backup.txt'
}, function(err) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.download().then(function(data) {
  const contents = data[0];
});
Run Code Online (Sandbox Code Playgroud)

请参阅以下链接了解更多详细信息: https://googleapis.dev/nodejs/storage/latest/File.html#download