根据 Google Drive API文档,上传文件的正确方法是:
curl -v -H 'Authorization: Bearer mytoken' -F 'metadata={"name": "test3.jpeg"};type=application/json' -F file=@jpeg_image.jpeg 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'
现在,我需要从 golang 代码执行相同的请求,但是我很难将其转换为 golang,这是我在多次尝试后使用的代码:
// fileBytes are of type []byte
buffer := &bytes.Buffer{}
multipartWriter := multipart.NewWriter(buffer)
multipartWriter.WriteField("metadata", "{\"name\": \"test3.jpef\"};type=application/json")
partHeader := textproto.MIMEHeader{}
partHeader.Add("Content-Type", "image/jpeg")
filePartWriter, _ := multipartWriter.CreatePart(partHeader)
io.Copy(filePartWriter, bytes.NewReader(fileBytes))
multipartWriter.Close()
googleDriveRequest, _ := http.NewRequest(http.MethodPost, "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", buffer)
googleDriveRequest.Header.Add("Authorization", "Bearer "+accessToken)
googleDriveRequest.Header.Add("Content-Type", multipartWriter.FormDataContentType())
googleDriveAPIResponse, googleDriveAPIError := lib.HttpClient.Do(googleDriveRequest)
使用 curl 请求成功:
{
"kind": "drive#file",
"id": "1DwsbQGP3-QtS5p0iQqRtAjcCCsAfxzGD",
"name": "test3.jpeg",
"mimeType": "image/jpeg"
}
使用 Golang,我得到 400:
{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"global\",\n \"reason\": \"badContent\",\n \"message\": \"Unsupported content with type: image/jpeg \"\n }\n ],\n \"code\": 400,\n \"message\": \"Unsupported content with type: image/jpeg\"\n }\n}\n
我也尝试了不同的值partHeader.Add("Content-Type", "image/jpeg")
,我也尝试过application/x-www-form-urlencoded
,我也注释掉了这一行,让 golang 进行检测,但仍然得到相同的错误。
有什么建议或想法吗?
问候,