gpt4 book ai didi

go - 从 golang 代码向 Google Drive API 发送文件产生错误 : Unsupported content with type: image/jpeg

转载 作者:数据小太阳 更新时间:2023-10-29 03:09:01 27 4
gpt4 key购买 nike

基于 Google Drive API docs上传文件的正确方法是:

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做检测,还是报同样的错误。

有什么建议或想法吗?

问候,

最佳答案

问题出在您发送的 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/

27 4 0
文章推荐: database - Gorm 只返回一个而不是多个结果
文章推荐: javascript - 添加逗号或空格以每三位数字分组
文章推荐: javascript - HTML