如何使用带有POST请求的python在Google云端硬盘上上传文件?

时间:2019-05-03 14:05:27

标签: python post google-drive-api python-requests

我正在尝试使用http POST请求在Google云端硬盘上上传文件,而没有Google库。

所以,这就是我在这里找到的:

import json
import requests

headers = {"Authorization": "Bearer " + ACCESS_TOKEN}
para = {
    "title": "image_url.jpg",
    "parents": [{"id": "root"}, {"id": "### folder ID ###"}]
}
files = {
    "data": ("metadata", json.dumps(para), "application/json; charset=UTF-8"),
    "file": requests.get("image_url").content
}
response = requests.post("https://www.googleapis.com/upload/drive/v2/files?  uploadType=multipart", headers=headers, files=files)

return response 

我试图对它进行一些调整以适合本地文件,并执行以下操作:

def upload_file(access_token, filename, filepath, parentID = "root"):
    query_link = 'https://www.googleapis.com/upload/drive/v3/files'
    query_params = "?uploadType=multipart"
    link = '{0}{1}'.format(query_link, query_params)
    headers = {"Authorization": "Bearer " + access_token}
    meta_data = {
        "title": filename,
        "parents": [{"id": parentID}]
    }
    files = {
        "data": ("metadata", json.dumps(meta_data), "application/json; charset=UTF-8"),
        "file": open(filepath + "\\" + filename, 'rb')
    }
    response = requests.post(link, headers=headers, files=files)

但是我所能做的就是在目录中创建无标题文件,所以您能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

找到解决方案。在第三版的Google Drive API中,他们使用字段名称代替标题,现在一切正常!