Home > Mobile >  Google Cloud Storage - How to access folders and files like static resources inside bucket - Spring
Google Cloud Storage - How to access folders and files like static resources inside bucket - Spring

Time:09-24

I want to use Google Cloud Storage for all static resources - images etc

The example is injecting 1 file, but I want to access many files - given a name

@Value("gs://${gcs-resource-test-bucket}/hello.txt")
private Resource gcsFile;

I am also not interested in iterating - as I have folders inside bucket, and dont want to iterqate all 100 files or so everytime

Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Page<Blob> blobs = storage.list(bucketName);

for (Blob blob : blobs.iterateAll()) {
  System.out.println(blob.getName());
}

Is there a way to access files like gs://somestringfilename ?

Don't know how to use this property to get access to files

You can also serve static resources by reading them from a bucket.
 spring.web.resources.static-locations=gs://p*

Assume that I have a rest controller to supply a file name, how can I get file from cloud storage?

CodePudding user response:

Based on the given statement, You are trying to read or access files from Google Cloud Storage using Java as your language.

For your case, this should work:

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.get(blobId);
String fileContent = new String(blob.getContent());
System.out.println(fileContent);

For further documentation of Class Blob, You may refer here.

You could also have a look into this Cloud Storage Client Libraries for more detail.

CodePudding user response:

I resolved this using bean

StorageOptions.newBuilder().setProjectId(projectId).build().getService();

a function

private Page folder(String directoryPrefix) {

Page<Blob> blobs =
        storage().list(
            bucketName,
            Storage.BlobListOption.prefix(directoryPrefix));

return blobs;       

}

Usage: directotyPrefix is not just my folder, but also sticking file name

myfolder/ filenamewithext

  • Related