How to access objects in google cloud storage?

2019-07-18 16:15发布

问题:

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.