通过Golang API将大文件上传到Google Drive

huangapple go评论91阅读模式
英文:

Upload large files to Google Drive via Golang API

问题

我正在使用google-api-go-client尝试将文件上传到Google Drive。我的代码与库中的示例代码非常相似:

goFile, err := os.Open(file_to_upload)
if err != nil {
  log.Fatalf("error opening file: %v", err)
}

file_meta := &drive.File{Title: filepath.Base(file_to_upload)}
_, err = service.Files.Insert(file_meta).Media(goFile).Ocr(true).Do()
if err != nil {
  panic(err)
}

这对我尝试的大多数文件都有效,但是对于一个5.1M的文件,我始终收到500错误。我认为这可能是因为该文件较大,而我测试的其他文件较小。我尝试过的最大成功文件大小为3.8M。

根据Google Files SDK的说明,我可能需要使用多部分上传。有没有人有任何示例Go代码,可以进行多部分上传到Google Drive?使用可用的alpha API是否可能?

英文:

I'm using the google-api-go-client to try to upload files to Google Drive. My code looks very similar to the example code in the library:

goFile, err := os.Open(file_to_upload)
if err != nil {
  log.Fatalf("error opening file: %v", err)
}

file_meta := &drive.File{Title: filepath.Base(file_to_upload)}
_, err = service.Files.Insert(file_meta).Media(goFile).Ocr(true).Do()
if err != nil {
  panic(err)
}

This works fine for most of the files I've tried, however I consistently get a 500 error for a 5.1M file. I think this is probably due to the fact that the file is larger and the other files I've tested are smaller. The largest successful file I've tried is 3.8M.

Looking at the Google Files SDK, it seems that I probably want to use a multipart upload. Does anyone have any example Go code that makes a multipart upload to Google Drive? Is it even possible with the alpha api available.

答案1

得分: 1

以下是翻译好的内容:

// 导入mime/multipart
// 导入path、net/http和bytes
uri := "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart"
body := &bytes.Buffer{}
w := multipart.NewWriter(body)
part, _ := w.CreateFormFile(fieldName, path.Base(fileName))
contentType := w.FormDataContentType()
_ = w.Close()
req, _ := http.NewRequest("POST", uri, body)
req.Header.Add("Content-Type", contentType)

请注意,这是一段Go语言代码,用于上传文件到Google Drive。它导入了mime/multipartpathnet/httpbytes等包,并使用multipart.NewWriter创建了一个multipart.Writer对象。然后,它创建了一个表单文件字段,并设置了相应的内容类型。最后,它创建了一个HTTP请求,并设置了请求头的内容类型。

英文:

Something on this line should work

// import mime/multipart  
//import path , net/http, bytes
uri := "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart"
body := &bytes.Buffer{}
w := multipart.NewWriter(body)
part, _:= w.CreateFormFile(fieldName, path.Base(fileName))
contentType := w.FormDataContentType()
_ = w.Close()
req, _ := http.NewRequest("POST", uri, body)
req.Header.Add("Content-Type", contentType)

huangapple
  • 本文由 发表于 2013年12月31日 10:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/20850726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定