python - 我可以仅使用 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
如果有人知道如何解决这个问题
解决方案
我相信你的目标如下。
- 您想使用 PyDrive 将图像数据从 URL 上传到 Google Drive。
- 从
f.SetContentFile(requests.get(p[:-1]).content)
,我了解到您想从 URL 下载图像数据并将其上传到 Google Drive。
- 从
修改点:
- 当我看到PyDrive的文档时,似乎
filename
是SetContentFile(filename)
本地PC的文件名(字符串值)。作为其他方法,似乎content
ofSetContentString(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)
推荐阅读
- java - 试图让用户输入的字符串保存双变量的值
- c - 为什么子进程运行代码意味着父进程
- python - 有没有办法从表格的两列生成 matplotlib 图?
- c# - 在 Visual Studio C# 中发出 Ping 请求
- javascript - 将嵌套的excel数据显示为json中的一个数据
- javascript - 如何向下滚动并在同一页面上显示部分?
- reactjs - 为什么在 React 中,render() 方法与“this”关键字配合得很好
- java - gradle如何将另一个子项目的代码和资源添加到子项目中
- sql - 使用和不使用 TIMEZONE 存储 DATETIME
- sql - SQL 拓扑排序