How to access objects in google cloud storage?

柔情痞子 提交于 2019-12-07 17:24:52

问题


I am trying to build an application that will access files in my google cloud storage while the bucket is private. The docs arent clear on what to do to enable access of the bucket from a server. I have the json file which they provide. I plan on using to expose the files on the bucket using nodejs but I'm not sure how to authorize requests to the bucket. I am using axios by the way. Do i create an API key or use a key as a query string? Some help would be appreciated!


回答1:


You want Google Cloud's Node.JS library: https://googlecloudplatform.github.io/google-cloud-node/#/

Here's an example of using it to access an object in 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);

There are several other examples on the GitHub page: https://github.com/GoogleCloudPlatform/google-cloud-node#preview-1

As well as extensive documentation here: https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/0.56.0/storage




回答2:


Try this:

        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()

Your file will be the "local file name" you mentioned. The above code is in Python.



来源:https://stackoverflow.com/questions/45331443/how-to-access-objects-in-google-cloud-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!