Google Drive API - 使用 cURL 分段上传

问题描述

我想让我的用户使用 API 将文件上传到他们 Google Drive 中的特定文件夹。我正在尝试使用分段上传类型,因此我可以按照此处的文档同时填充元数据和文件本身:

https://developers.google.com/drive/api/v3/manage-uploads#http_1

我希望能够看到有关如何执行此操作的 cURL 请求示例,但 Drive 文档中的“尝试此 API”工具似乎确实支持这一点,我也找不到任何示例在线其他地方:

https://developers.google.com/drive/api/v3/reference/files/create?apix=true

我已经开始构建一个 cURL 请求,但我不知道如何以这种方式发送实际文件。

curl --request POST \
  'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: multipart/related' \
  --data '{"name":"file_name.pdf","mimeType":"application/vnd.google-apps.file","parents":["parent_folder_id"]}' \
  --compressed

我一直在使用 NET::HTTP for ruby​​ 来构建这些请求。我之前使用过谷歌的 Ruby 库,但它的文档充其量是不完整的,所以我已经恢复到 NET::HTTP 因为谷歌的文档通常有明确的 cURL/HTTP 示例。

这是我目前用 Ruby 编写的相关代码:

        folder_id = user.google_folder_id
        name = "#{title}.pdf"
        uri = URI.parse("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart")
        request = Net::HTTP::Post.new(uri)
        request["Authorization"] = "Bearer #{user.google_access_token}"
        request["Accept"] = "application/json"
        request.content_type = "multipart/related"
        request["Content-Length"] = "1000"
        request.body = JSON.dump({
          "content_type" => "application/json; charset=UTF-8","parents" => [
            "#{folder_id}"
          ],"name" => "#{name}.pdf","mimeType" => "application/vnd.google-apps.file",})
        request.set_form([['upload',File.open("#{filename}parse.pdf")]],'multipart/form-data')

        req_options = {
          use_ssl: uri.scheme == "https",}

        response = Net::HTTP.start(uri.hostname,uri.port,req_options) do |http|
          http.request(request)
        end

        response = JSON.parse(response.body)
        puts response

返回的响应如下:

{"error"=>{"errors"=>[{"domain"=>"global","reason"=>"badContent","message"=>"Unsupported content with type: application/octet-stream"}],"code"=>400,"message"=>"Unsupported content with type: application/octet-stream"}}

非常感谢任何帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)