gpt4 book ai didi

python - 使用 python 请求库将文件上传到谷歌云存储时出错

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:43 25 4
gpt4 key购买 nike

我正在使用 rest api 将文件上传到谷歌云存储

用 curl 就可以了

curl -X POST --data-binary @[OBJECT] \
-H "Authorization: Bearer [OAUTH2_TOKEN]" \
-H "Content-Type: [OBJECT_CONTENT_TYPE]" \
"https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[OBJECT_NAME]"

但使用 python 请求后文件上传已损坏

import requests
filepath = '/home/user/gcs/image.jpg'
url = 'https://www.googleapis.com/upload/storage/v1/b/****/o?uploadType=media&name=image.jpg'
authorization = 'Bearer ******'

headers = {
"Authorization": authorization,
"Content-Type": "image/jpeg",
}

with open(filepath, "rb") as image_file:
files = {'media.jpeg': image_file}
r = requests.post(url, headers=headers, files=files)
print(r.content)

最佳答案

您正在调用的上传方法要求请求正文包含您正在上传的数据。这就是 curl --data-binary 选项的作用。但是 requests.post(files=BLAH)多部分编码您的数据,这不是您想要的。相反,您想使用数据参数:

with open(filepath, "rb") as image_file:
r = requests.post(url, headers=headers, data=image_file)
print(r.content)

关于python - 使用 python 请求库将文件上传到谷歌云存储时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45948354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com