【发布时间】:2019-06-26 20:22:13
【问题描述】:
我正在尝试将大文件(大于 5 MB)上传到 Google 云端硬盘。基于谷歌的documentation,我需要设置一个可恢复的上传会话。如果会话成功启动,您将收到带有会话 URI 的响应。然后使用我认为是您的文件向 URI 发送另一个请求。
我已经能够成功设置可恢复会话,但我不清楚您指定文件的位置以使用此方法上传。请在下面查看我的代码。
Google 希望启动 Resumable Upload
POST https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: application/octet-stream
{
"name": "myObject"
}
我是如何在 Python 中做到的
import requests
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
keyfile_dict=[SERVICE_ACCOUNT_JSON],
scopes='https://www.googleapis.com/auth/drive')
delegated_credentials = credentials.create_delegated([EMAIL_ADDRESS])
access_token = delegated_credentials.get_access_token().access_token
url = "https://www.googleapis.com/upload/drive/v3/files"
querystring = {"uploadType": "resumable"}
payload = '{"name": "myObject", "parents": "[PARENT_FOLDER]"}'
headers = {
'Content-Length': "38",
'Content-Type': "application/json",
'X-Upload-Content-Type': "application/octet-stream",
'Authorization': "Bearer " + access_token
}
response = requests.request(
"POST", url, data=payload, headers=headers, params=querystring)
print(response.headers['Location'])
成功的响应位置 URI
https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=[SOME_LONG_ID]
Google 想要的 PUT 请求
PUT https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=[SOME_LONG_ID] HTTP/1.1
Content-Length: 2000000
Content-Type: application/octet-stream
[BYTES 0-1999999]
python 中的 PUT 请求 - 这是我开始迷路的地方
uri = response.headers['Location']
headers = {
'Content-Length': "2000000",
'Content-Type': "application/json"
}
response = requests.request(
"PUT", uri, headers=headers)
我想知道如何使用我的文件路径和任何其他所需信息来完成此 PUT 请求。感谢您的帮助。
【问题讨论】:
-
在 [SERVICE_ACCOUNT_JSON] 你把路径到 Json 文件?在 [EMAIL_ADDRESS] 服务帐户电子邮件的字符串?
标签: python file-upload google-drive-api