按照 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中文网其他相关文章!