使用 pydrive 将图像字符串上传到 Google Drive 示例脚本:注意:参考:

问题描述

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

SetContentString 需要类型为 str 而不是 bytes 的参数。

但是出现了错误UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte,如对该答案的评论中所述。
有没有办法在不使用临时文件的情况下做到这一点,使用 PIL/BytesIO/anything 可以将其转换为字符串正确上传或以某种方式使用 PIL 作为图像操作并使用 { 上传{1}}?

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

SetContentFile()

解决方法

当我看到pydrive的文档(Upload and update file content)时,它是这样写的。

管理文件内容就像管理文件元数据一样简单。您可以使用 SetContentFile(filename) 或 SetContentString(content) 设置文件内容并调用 Upload(),就像您上传或更新文件元数据一样。

而且,我搜索了将二进制数据直接上传到Google Drive的方法。但是,我找不到。从这种情况来看,我认为可能没有这种方法。所以,在这个答案中,我想建议使用 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 是图像文件的直接链接。请注意这一点。

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

    使用此上传类型可在单个请求中快速传输小文件(5 MB 或更少)和描述文件的元数据。要执行分段上传,请参阅执行分段上传。

    • 当你想上传大尺寸的数据时,请使用可续传。 Ref

参考: