按照 go 範例,我使用以下程式碼將檔案上傳到 google 儲存桶:
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) } }
現在我計劃將其包裝起來,創建一個用於文件上傳的 rest api。然後我意識到該程式碼僅用於上傳本機檔案。如何包裝它以便文件直接進入儲存桶,而不需要先將其上傳到伺服器?
有很多檔案上傳範例,重點是:
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() // ... }
因此,只需將文件上傳的 f
主體傳遞到您的雲端上傳邏輯,就好像它是本機檔案一樣:
// 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) }
以上是使用 REST API 將檔案直接上傳到 Google 儲存桶的詳細內容。更多資訊請關注PHP中文網其他相關文章!