Upload large files to Google Drive via Golang API

3k views Asked by At

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

There are 1 answers

0
Minty On

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)