我正在尝试构建一个应用程序,当存储桶处于私有状态时,该应用程序将访问我的Google云存储中的文件。文档不清楚如何从服务器访问存储桶。我有他们提供的json文件。我打算使用nodejs来暴露存储桶上的文件,但我不知道如何授权对存储桶的请求。我顺便使用axios。我是否创建API密钥或使用密钥作为查询字符串?一些帮助将不胜感激!
答案 0 :(得分:3)
您需要Google Cloud的Node.JS库:https://googlecloudplatform.github.io/google-cloud-node/#/
以下是使用它访问GCS中对象的示例:
var config = {
projectId: 'grape-spaceship-123',
keyFilename: '/path/to/keyfile.json'
};
var storage = require('@google-cloud/storage')(config);
var bucket = gcs.bucket('my-existing-bucket');
var remoteReadStream = bucket.file('giraffe.jpg').createReadStream();
remoteReadStream.pipe(someLocalWriteStream);
GitHub页面上还有其他一些示例:https://github.com/GoogleCloudPlatform/google-cloud-node#preview-1
此处还有大量文档: https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/0.56.0/storage
答案 1 :(得分:0)
试试这个:
scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
cred = ServiceAccountCredentials.from_json_keyfile_name('<path to .json credential file>', scopes)
bucket = '<your bucket name>'
google_service = build('storage', 'v1', credentials=cred)
req = google_service.objects().get_media(bucket=bucket,object='<your cloud object name>')
media = MediaIoBaseDownload(<local file name>, req, chunksize=1024*1024)
resp = None
while resp is None:
status, resp = media.next_chunk()
您的文件将是您提到的“本地文件名”。上面的代码是Python。