使用 pydrive 将图像字符串上传到 Google 驱动器

Uploading image string to Google Drive using pydrive

我需要使用 PyDrive 包将图像字符串(如您从 requests.get(url).content 获得的字符串)上传到 google 驱动器。我检查了 但接受的答案是将其保存在本地驱动器上的临时文件中,然后上传。
但是,由于本地存储和权限限制,我不能这样做。
接受的答案之前是使用 SetContentString(image_string.decode('utf-8')) since

SetContentString requires a parameter of type str not bytes.

但是出现了错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte,如对该答案的评论中所述。
有没有什么方法可以在不使用临时文件的情况下执行此操作,使用 PIL/BytesIO/任何可以将其转换为作为字符串正确上传或以某种方式使用 PIL 作为图像处理并使用 SetContentFile()?

我正在尝试做的一个基本示例是:

img_content = requests.get('https://i.imgur.com/A5gIh7W.jpeg')
file = drive.CreateFile({...})
file.setContentString(img_content.decode('utf-8'))
file.Upload()

看到pydrive的文档(Upload and update file content),是这样说的

Managing file content is as easy as managing file metadata. You can set file content with either SetContentFile(filename) or SetContentString(content) and call Upload() just as you did to upload or update file metadata.

并且,我搜索了将二进制数据直接上传到Google驱动器的方法。但是,我找不到它。从这种情况来看,我认为可能没有这样的方法。因此,在这个答案中,我想建议使用 requests 模块上传二进制数据。在这种情况下,访问令牌是从 pydrive 的授权脚本中检索的。示例脚本如下

示例脚本:

from pydrive.auth import GoogleAuth
import io
import json
import requests


url = 'https://i.imgur.com/A5gIh7W.jpeg' # Please set the direct link of the image file.
filename = 'sample file' # Please set the filename on Google Drive.
folder_id = 'root' # Please set the folder ID. The file is put to this folder.

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
metadata = {
    "name": filename,
    "parents": [folder_id]
}
files = {
    'data': ('metadata', json.dumps(metadata), 'application/json'),
    'file': io.BytesIO(requests.get(url).content)
}
r = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers={"Authorization": "Bearer " + gauth.credentials.access_token},
    files=files
)
print(r.text)

注:

  • 在这个脚本中,它假设你的URL是图像文件的直接link。请注意这一点。

  • 在这种情况下,使用uploadType=multipart。官方文档是这样说的。 Ref

    Use this upload type to quickly transfer a small file (5 MB or less) and metadata that describes the file, in a single request. To perform a multipart upload, refer to Perform a multipart upload.

    • 上传大尺寸数据时,请使用断点续传。 Ref

参考文献: