基于 Google Drive API docs上传文件的正确方法是:
curl -v -H '授权:不记名 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进行检测,但仍然得到相同的错误。
有什么建议或想法吗?
问候,
最佳答案
问题出在您发送的 JSON 元数据中。这是一个可以工作的示例代码(使用适当的错误检查),
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/textproto"
)
func main() {
accessToken := "YOUR-TOKEN"
client := http.Client{}
mediaData, _ := ioutil.ReadFile("test.png")
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// JSON Metadata (part-1)
jsonMetadata := textproto.MIMEHeader{}
metadata := `{"name": "test.png"}`
jsonMetadata.Set("Content-Type", "application/json")
part, _ := writer.CreatePart(jsonMetadata)
part.Write([]byte(metadata))
// Image bytes (part-2)
imageData := textproto.MIMEHeader{}
partAttach, _ := writer.CreatePart(imageData)
io.Copy(partAttach, bytes.NewReader(mediaData))
writer.Close()
// Request Content Type with boundary
contentType := fmt.Sprintf("multipart/related; boundary=%s", writer.Boundary())
// HTTP Request with auth and content type headers
req, _ := http.NewRequest(http.MethodPost, "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", bytes.NewReader(body.Bytes()))
req.Header.Add("Authorization", "Bearer "+accessToken)
req.Header.Add("Content-Type", contentType)
// Send request
resp, err := client.Do(req)
if err != nil {
log.Fatalf("failed to send request: %v", err)
}
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
log.Printf("http status: %d", resp.StatusCode)
log.Printf("response: %s", string(content))
}
引用:https://developers.google.com/drive/api/v3/manage-uploads?authuser=1#send_a_multipart_upload_request
关于go - 从 golang 代码将文件发送到 Google Drive API 会产生错误 : Unsupported content with type: image/jpeg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55576032/