我在用着@google-cloud/存储 https://www.npmjs.com/package/@google-cloud/storage从节点应用程序访问 Google Cloud Storage 存储桶内的对象,但我无法使其工作。
我已在 GCP 控制台上创建了一个服务帐号,并分配了存储管理员角色,但是当我尝试获取文件时,我收到以下消息:
[电子邮件受保护] /cdn-cgi/l/email-protection没有 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);
});
关于我做错了什么有什么想法吗?
我可以使用下载该文件Storage Admin Role
。以下是我遵循的过程
1. Create Project
2. 进入IAM并选择服务账户
3. Select create-service account
4. select role for service account
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()
Note: 确保
-
在项目下创建服务帐户和存储桶。例如,我为项目创建了一个存储桶和服务帐户存储-dem01232020
-
您正在正确地将密钥传递给代码
下载文件的方式
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];
});
请参阅以下链接了解更多详细信息:https://googleapis.dev/nodejs/storage/latest/File.html#download https://googleapis.dev/nodejs/storage/latest/File.html#download
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)