documentation on insert operations 已经包含多种编程语言的示例,这里是如何使用基于 HTTP 的 Google Drive API 协议来实现的。
首先,将新文件元数据发布到云端硬盘端点。它必须采用File resource JSON object 的形式:
POST /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
...
{
"title": "file_name.extension",
"mimeType": "mime/type",
"description": "Stuff about the file"
}
响应正文将是新创建的文件资源的 JSON 表示。它看起来像:
{
"kind": "drive#file",
"id": string,
"etag": etag,
"selfLink": string,
"title": "file_name",
"mimeType": "mime/type",
"description": "Stuff about the file"
...
"downloadUrl": string,
...
}
这是对文件条目已创建的确认。现在您需要上传内容。为此,您需要获取上述响应中 id JSON 属性给出的文件 ID,并将实际文件的内容通过 OAuth 2.0 授权请求发送到上传端点。它应该看起来像:
PUT /upload/drive/v2/files/{id}?uploadType=media HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: mime/type
<file content here>
你已经完成了:)
还有一种方法可以在单个 POST 请求中使用多部分请求来执行此操作,您可以在该请求中将文件的元数据与内容同时发布。这是一个例子:
POST /upload/drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: multipart/form-data; boundary=287032381131322
...
--287032381131322
Content-Type: application/json
{
"title": "file_name.extension",
"mimeType": "mime/type",
"description": "Stuff about the file"
}
--287032381131322
Content-Type: mime/type
<file content here>
--287032381131322--
响应将包含新创建文件的元数据。
您还可以在请求的子部分中使用 Content-Transfer-Encoding: base64 标头,以便能够将文件数据作为 Base 64 编码传递。
最后还有一个resumable upload protocol,方便上传大文件、提供暂停/恢复功能和/或上传互联网连接不稳定的文件。
PS:大部分内容现在在Drive's file upload documentation 中进行了描述。