dqyp50298 2019-04-08 14:44
浏览 65
已采纳

从golang代码将文件发送到Google Drive API会产生错误:类型为image / jpeg的内容不受支持

based on the Google Drive API docs the proper way of uploading a file is:

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'

Now, I need to perform the same request from golang code, but I am having a hard time translating this to golang, here is the code I am using after several attempts:

// 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)

Using curl the request succeeds :

{
 "kind": "drive#file",
 "id": "1DwsbQGP3-QtS5p0iQqRtAjcCCsAfxzGD",
 "name": "test3.jpeg",
 "mimeType": "image/jpeg"
}

With Golang, I get a 400:

{
 \"error\": {
  \"errors\": [
   {
    \"domain\": \"global\",
    \"reason\": \"badContent\",
    \"message\": \"Unsupported content with type: image/jpeg \"
   }
  ],
  \"code\": 400,
  \"message\": \"Unsupported content with type: image/jpeg\"
 }
}

I also tried with different values for partHeader.Add("Content-Type", "image/jpeg"), I tried with application/x-www-form-urlencoded as well, I also commented out this line, and let golang do the detection, but still getting the same error.

Any suggestions or ideas?

Regards,

  • 写回答

1条回答 默认 最新

  • doujiufutaog59220 2019-04-08 15:50
    关注

    The problem is in the JSON metadata that you send. Here is a sample code (use proper error checking) that will work,

    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))
    }
    

    Reference: https://developers.google.com/drive/api/v3/manage-uploads?authuser=1#send_a_multipart_upload_request

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)