Home  >  Article  >  Backend Development  >  Upload files directly to Google Bucket using REST API

Upload files directly to Google Bucket using REST API

WBOY
WBOYforward
2024-02-05 23:15:03513browse

使用 REST API 将文件直接上传到 Google 存储桶

Question content

Following the go example, I used the following code to upload files to google bucket:

func uploadFile(bucket string, uploadFilePath string, destFilePath string) error {
    os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "./credential.json")
    ctx := context.Background()
    client, err := storage.NewClient(ctx)
    if err != nil {
        return fmt.Errorf("storage.NewClient: %v", err)
    }
    defer client.Close()

    // Open local file.
    f, err := os.Open(uploadFilePath)
    if err != nil {
        return fmt.Errorf("os.Open: %v", err)
    }
    defer f.Close()

    ctx, cancel := context.WithTimeout(ctx, time.Second*50)
    defer cancel()
    o := client.Bucket(bucket).Object(destFilePath)
    o = o.If(storage.Conditions{DoesNotExist: true})
    
    // Upload an object with storage.Writer.
    wc := o.NewWriter(ctx)
    if _, err = io.Copy(wc, f); err != nil {
        return fmt.Errorf("io.Copy: %v", err)
    }
    if err := wc.Close(); err != nil {
        return fmt.Errorf("Writer.Close: %v", err)
    }
    return nil
}

func main() {
    bucket := "g1-mybucket-001"
    targetFilePath := "./somefile.txt"
    destFilePath := "it_poc_test_folder/somefile.txt"
    err := uploadFile(bucket, targetFilePath, destFilePath)
    if err != nil {
        fmt.Println(fmt.Errorf("Error uplolading file: %v", err))
    } else {
        fmt.Printf("%s uploaded to %s.\n", targetFilePath, destFilePath)
    }
}

Now I plan to wrap it up and create a rest api for file upload. Then I realized that the code is only for uploading local files. How do I wrap it so that the file goes directly into the bucket without uploading it to the server first?


Correct answer


There are many files to uploadExample, the main points are:

func uploadfile(w http.responsewriter, r *http.request) {

    // ... 
    r.parsemultipartform(10 << 20)
    f, handler, err := r.formfile("myfile")
    if err != nil {
        // handle err
    }
    defer f.close()
    // ...
}

So just pass the f body of the file upload to your cloud upload logic as if it were a local file:

// same code - different `f` source

// Upload an object with storage.Writer.
wc := o.NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
    return fmt.Errorf("io.Copy: %v", err)
}

The above is the detailed content of Upload files directly to Google Bucket using REST API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete