使用pydrive将图像字符串上载到Google Drive

2024-09-29 01:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

Tags: 字符串答案图像urlimggetpilcontent
1条回答
网友
1楼 · 发布于 2024-09-29 01:19:17

当我看到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.

我还搜索了直接将二进制数据上传到谷歌硬盘的方法。但是,我找不到它。从这种情况来看,我认为可能没有这样的方法。因此,在这个答案中,我建议使用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

    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

参考文献:

相关问题 更多 >