'How to upload files to Google Cloud Storage Bucket subdirectory

I want to upload files to google cloud storage bucket subdirectories using Go. The only reference code I found is link.

wc := client.Bucket(bucket).Object(object).NewWriter(ctx)

The object here is a string of your file name but the file path is not allowed. It will throw the following error when I use a file name like /path/filename. It works only if you use filename.

connect: can't assign requested address

Previously I use node.js and it works fine.

await bucket.upload(filePath, { destination: `path/filename`, resumable:false });

How can I achieve that with Go?



Solution 1:[1]

Continuing with the Node example, the bucket is always the top-level bucket name.

Subdirectories become part of the "file". GCP thinks of the subdirectory(ies) + the file as an object. Yes, it is counter-intuitive.


const bucketName = 'top-level-bucket-name';
const subBucketName = 'sub_level/another_sub_level/';
// Cloud Function uses /tmp not ./tmp
const directory = './tmp'; 
const fileName = 'foo.txt';

storage.bucket(bucketName).upload(`${directory}/${fileName}`, { destination: subBucketName + fileName});

I ran into an issue with hyphens in subdirectories not working, which is why there are underscores instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1