Google api 如何使用google drive api将jpg上传到google drive?

Google api 如何使用google drive api将jpg上传到google drive?,google-api,google-drive-api,Google Api,Google Drive Api,我正试图使用api将一个jpg文件上传到谷歌硬盘上,但我运气不太好。虽然代码运行时没有错误,但保存在我的谷歌硬盘中的“图像”没有标题,实际上并不包含数据 下面是我现在在Python中的实现方式: post_body = "grant_type=refresh_token&client_id={}&client_secret={}&refresh_token={}".format(client_id, client_secret, refresh_tok

我正试图使用api将一个jpg文件上传到谷歌硬盘上,但我运气不太好。虽然代码运行时没有错误,但保存在我的谷歌硬盘中的“图像”没有标题,实际上并不包含数据

下面是我现在在Python中的实现方式:

post_body = "grant_type=refresh_token&client_id={}&client_secret={}&refresh_token={}".format(client_id, client_secret, refresh_token)

r = requests.post(refresh_url, data=post_body, headers={"Content-Type" : "application/x-www-form-urlencoded"})

r_json = json.loads(r.text)
access_token = r_json["access_token"]

media = MediaFileUpload(filename, mimetype="image/jpeg", resumable=True)

body = {
        "name" : filename,
        "mimeType" : "image/jpeg"
       }

drive_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
drive_r = requests.post(drive_url, data=body, headers={"Authorization": "Bearer " + access_token, "Content-type": "image/jpeg"})
当我打印drive_r.text时,我得到的响应是:

{
 "kind": "drive#file",
 "id": "1Vt4gP***************",
 "name": "Untitled",
 "mimeType": "image/jpeg"
}

从您的脚本中,我了解到您希望在不使用googleapis for Python的情况下将文件上载到Google Drive。在这种情况下,我想提出以下修改

修改点:
  • 在脚本中,文件中的数据不包括在请求正文中
  • 您可以使用
    uploadType=media
    。但是您似乎希望包含文件元数据。在这种情况下,请使用
    uploadType=multipart
模式1: 如果要上载的文件大小小于5 MB,可以使用以下脚本<使用代码>上传类型=多部分

修改脚本: 模式2: 如果要上载的文件大小超过5 MB,可以使用以下脚本<使用代码>上传类型=可恢复

修改脚本: 注:
  • 这些示例脚本假定您的访问令牌可用于将文件上载到Google Drive
参考:
import json
import requests

access_token = r_json["access_token"] # This is your script for retrieving the access token.
filename = '###'  # Please set the filename with the path.

para = {"name": filename}
files = {
    'data': ('metadata', json.dumps(para), 'application/json'),
    'file': open(filename, "rb")
}
r = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers={"Authorization": "Bearer " + access_token},
    files=files
)
print(r.text)
import json
import os
import requests

access_token = r_json["access_token"] # This is your script for retrieving the access token.
filename = '###'  # Please set the filename with the path.

filesize = os.path.getsize(filename)
params = {
    "name": filename,
    "mimeType": "image/jpeg"
}
r1 = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
    headers={"Authorization": "Bearer " + access_token, "Content-Type": "application/json"},
    data=json.dumps(params)
)
r2 = requests.put(
    r1.headers['Location'],
    headers={"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)},
    data=open(filename, 'rb')
)
print(r2.text)