Search code examples
imagegogoogle-cloud-platformgoogle-cloud-storagegoogle-cloud-sdk

Golang upload image to GCS with specific path


I had stuck with Google Cloud Storage and os.create()

This is my example code

func upload(w http.ResponseWriter, r *http.Request) {
     // some process request msg, decode base64 to image byte
    // create image file in current directory with os.create()
    // 
    path := os.create("shop_logo.jpeg")
    bucket := client.Bucket("myBucket")
    write := bucket.Object(path).NewWriter(ctx)
     
}

Create file with directory

func upload(w http.ResponseWriter, r *http.Request) {
     // some process request msg, decode base64 to image byte
    // create image file in current directory with os.create()
    // 
    path := os.create("home/../project/repo/shop_logo.jpeg") //absolute path
    bucket := client.Bucket("myBucket")
    write := bucket.Object(path).NewWriter(ctx)
     
}

Acutally everything it work, like mybucket/shop_logo.jpeg
But I want to organize the bucket path such as mybucket/shop_v1/shop_logo.jpeg
But the I used the os.create() like os.create("shop_v1/shop_logo.jpeg)
It's can't work, look like this function can't create the folder.
but when I used the Absolute Path It's work. like os.create("/home/project/shop_v1/shop_logo.jpeg)
The problem is bucket.Object("path/to/image_file") is require the path of file.
So If I used the Absolute Path to upload it.
My bucket will be myBucket/home/project/shop_v1/shop_logo.jpeg .

But the thing that I expect it is mybucket/shop_v1/shop_logo.jpeg

Anyone have idea?


Solution

  • Oh, I just found the os.create() can create directory also.

    It my fault like this

    inputPath := "/shop_v1/shop_logo.jpeg"
    os.create(inputPath)
    

    The application will error, can't find blah blah.
    I just have to remove the first slash of inputPath variable

    inputPath := "shop_v1/shop_logo.jpeg"
    os.create(inputPath)
    

    Now it work!.