Sending file to Google drive API from golang code yields error: Unsupported content with type: image/jpeg
Sending file to Google drive API from golang code yields error: Unsupported content with type: image/jpeg
基于Google驱动器APIdocs上传文件的正确方法是:
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
基于Google驱动器APIdocs上传文件的正确方法是:
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