Google Drive API "Post" 方法,上传带有元数据的图像文件,Python

Google Drive API "Post" Method, uploading an image file with meta data, Python

我正在尝试上传包含 Python 中元数据的图像文件。

我知道有一个非常方便的Python API,但我想使用“Post”方法,这样我就可以使用“aiohttp”了。

看了官方文档,自己编码如下,400错误

这是怎么回事?

import requests
import json
import sys

with open('storage.json', 'r') as file:
    token = json.load(file)
    token = token["access_token"]

url = 'https://www.googleapis.com/upload/drive/v3/files'
file_metadata = {
    'Content-Type': 'application/json; charset=UTF-8',
    'name': 'test.jpg',
    'parents': [],
    'mimeType': None
}
media = {
    'Content-Type': 'image/jpeg',
    'file': open('test2.jpg', 'rb'),
}
data = {
    'MetaData': file_metadata,
    'Media': media,
}

headers = {
    'Authorization': 'Bearer {}'.format(token),
    'Content-Type': 'multipart/related',
    'Content-Length': str(sys.getsizeof(data)),
}
params = {
    'uploadType': 'multipart'
}

res = requests.post(url, data=data, params=params, headers=headers)
print(res)

我想,你快到目的地了,把data参数改成json意思是用json = data代替data = data

import requests
import json
import sys

with open('storage.json', 'r') as file:
    token = json.load(file)
    token = token["access_token"]

url = 'https://www.googleapis.com/upload/drive/v3/files'
file_metadata = {
    'Content-Type': 'application/json; charset=UTF-8',
    'name': 'test.jpg',
    'parents': [],
    'mimeType': None
}
media = {
    'Content-Type': 'image/jpeg',
    'file': open('test2.jpg', 'rb'),
}
data = {
    'MetaData': file_metadata,
    'Media': media,
}

headers = {
    'Authorization': 'Bearer {}'.format(token),
    'Content-Type': 'multipart/related',
    'Content-Length': str(sys.getsizeof(data)),
}
params = {
    'uploadType': 'multipart'
}

res = requests.post(url, json=data, params=params, headers=headers)
print(res)

在你的脚本中,做如下修改怎么样?

修改后的脚本:

import requests
import json

with open('storage.json', 'r') as file:
    token = json.load(file)
    token = token["access_token"]

url = "https://www.googleapis.com/upload/drive/v3/files"
file_metadata = {"name": "test.jpg"}
data = {
    "MetaData": (
        "metadata",
        json.dumps(file_metadata),
        "application/json; charset=UTF-8",
    ),
    "Media": open("test2.jpg", "rb"),
}

headers = { "Authorization": "Bearer {}".format(token) }
params = {"uploadType": "multipart"}

res = requests.post(url, files=data, params=params, headers=headers)
print(res.text)

测试:

当此脚本为运行时,返回如下结果。

{
 "kind": "drive#file",
 "id": "###",
 "name": "test.jpg",
 "mimeType": "image/jpeg"
}

在这种情况下,文件被上传到根文件夹。当你想把文件放到特定的文件夹时,请在file_metadata中加上'parents': ['###folderId###']

参考: