我需要使用PyDrive包将一个图像字符串(正如您从requests.get(url).content
)上传到googledrive。我检查了一个similar question,但答案是将其保存在本地驱动器上的临时文件中,然后上传
但是,由于本地存储和权限限制,我不能这样做
公认的答案是以前使用SetContentString(image_string.decode('utf-8'))
,因为
SetContentString
requires a parameter of typestr
notbytes
.
然而,出现了错误: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)时,它显示如下
我还搜索了直接将二进制数据上传到谷歌硬盘的方法。但是,我找不到它。从这种情况来看,我认为可能没有这样的方法。因此,在这个答案中,我建议使用
requests
模块上传二进制数据。在这种情况下,从pydrive的授权脚本中检索访问令牌。示例脚本如下所示示例脚本:
注:
在这个脚本中,它假设您的URL是图像文件的直接链接。请小心这个
在这种情况下,使用
uploadType=multipart
。官方文件如下Ref参考文献:
相关问题 更多 >
编程相关推荐