我正在尝试使用RestClient将一个小图像文件上传到Google云端硬盘。 我已经有一个访问令牌(在早期的代码中请求),但我不确定如何形成有效负载。
API 文档声明请求应如下所示:
POST /upload/drive/v3/files?uploadType=media HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Content-Length: number_of_bytes_in_file
Authorization: Bearer your_auth_token
JPEG data
我尝试了以下方法,但会导致错误:
require 'rest-client'
file = File.open("./uploaded-by-api.jpg")
response = RestClient::Request.execute(method: :post, url: 'https://www.googleapis.com/upload/drive/v3/files', payload: { uploadType: "media", file: file, }, headers: { Authorization: "Bearer #{access_token}", "Content-Type" => "image/jpeg", "Content-Length" => "1000" })
我很确定我包含实际文件数据的方式存在错误,但我在 RestClient 中找不到任何示例。
Ok 用以下内容解决了它:
response = RestClient.post(
'https://www.googleapis.com/upload/drive/v3/files',
{ 'uploadType' => "media", 'upload' => file },
"Authorization" => "Bearer #{access_token}",
"Content-Type" => "image/jpeg",
"Content-Length" => "1000"
)