Renato
Renato

Reputation: 121

How can I access a file of storage with dart Google Storage API

I'm trying to get information of a file that is inside of a folder in Google cloud Storage (not firebase storage). But the API of it in Dart language is not complete, it doesn't have a function to show the blob (file) information like we have in python same API. I just need to access the name of the file. Here's my code:

var credentials = auth.ServiceAccountCredentials.fromJson({
    "type": "service_account",
     ...
  });

  List<String> scopes = []..addAll(Storage.SCOPES);

  var client = await auth.clientViaServiceAccount(credentials, scopes);

  var storage = Storage(client, "project_name");
  var bucket = storage.bucket("Bucket_name");


  var list = await bucket.read("folder_name/");

  list.forEach((element) {
    print(element.toString());
  });

It has a lot of options like toList(),toSet(), asBroadcastStream() and etc. But any of these return me what I need. Some ones just return a empty list, that doesn't make sence for me.

Anyways, if someone know how to read data from a folder of GCP storage, please anwser me. Sorry for my english and Thanks!

The API docs: https://pub.dev/documentation/gcloud/latest/gcloud.storage/gcloud.storage-library.html

Upvotes: 1

Views: 1588

Answers (2)

guillaume blaquiere
guillaume blaquiere

Reputation: 75820

For you backend, you can use bucket.list(prefix: "folder_name/","") as described in the documentation:

Listing operates like a directory listing, despite the object namespace being flat. Unless delimiter is specified, the character / is being used to separate object names into directory components. To list objects recursively, the delimiter can be set to empty string.

For the front end, forget this! You can't provide a service account key file in your frontend! If you share the secret publicly, it's like if you set your bucket public!

So, for this, you need to have a backend that authenticated the user and generate a signed URL to read and write inside the bucket.

Upvotes: 1

David
David

Reputation: 9721

bucket.read() gets the contents of individual objects. If you want to get the object names, use bucket.list().

Upvotes: 0

Related Questions