首页 > 解决方案 > 我可以仅使用 url 在 GDrive 中上传图像吗?

问题描述

所以我尝试通过 url 直接上传到 gdrive 而不下载图像

f.SetContentFile(requests.get(p[:-1]).content)

但我知道 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 如果有人知道如何解决这个问题

标签: pythonurlgoogle-drive-api

解决方案


我相信你的目标如下。

  • 您想使用 PyDrive 将图像数据从 URL 上传到 Google Drive。
    • f.SetContentFile(requests.get(p[:-1]).content),我了解到您想从 URL 下载图像数据并将其上传到 Google Drive。

修改点:

  • 当我看到PyDrive的文档时,似乎filenameSetContentFile(filename)本地PC的文件名(字符串值)。作为其他方法,似乎contentofSetContentString(content)是字符串值。

所以为了上传下载的图像数据,我想建议使用requests模块。在这种情况下,上传的访问令牌是从 PyDrive 的授权中检索的。

当以上几点反映到脚本中时,它变成如下。

示例脚本:

from pydrive.auth import GoogleAuth
# from pydrive.drive import GoogleDrive # In this script, this is not used.
import io
import json
import requests


gauth = GoogleAuth()
gauth.LocalWebserverAuth()

url = "###" # Please set the URL of direct link of the image.
filename = 'sample file' # Please set the filename.
folder_id = 'root' # Please set the folder ID. If 'root' is used, the uploaded file is put to the root folder.

access_token = gauth.attr['credentials'].access_token
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 " + access_token},
    files=files
)
print(r.text)
  • 在此脚本中,下载的图像文件直接上传到 Google Drive,无需创建临时文件。

结果:

运行上述脚本时,将返回以下结果。

{
 "kind": "drive#file",
 "id": "###",
 "name": "sample file",
 "mimeType": "image/###"
}

参考:

添加:

关于您的第二个问题,当您想将文件创建到共享驱动器时,请按如下方式修改上述脚本。

示例脚本:

from pydrive.auth import GoogleAuth
# from pydrive.drive import GoogleDrive # In this script, this is not used.
import io
import json
import requests


gauth = GoogleAuth()
gauth.LocalWebserverAuth()

url = "###" # Please set the URL of direct link of the image.
filename = 'sample file' # Please set the filename.
folder_id = '###' # Please set the folder ID of the shared Drive. When you want to create the file to the root folder of the shared Drive, please set the Drive ID here.

access_token = gauth.attr['credentials'].access_token
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&supportsAllDrives=true",
    headers={"Authorization": "Bearer " + access_token},
    files=files
)
print(r.text)

推荐阅读