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

时间:2017-08-29 21:08:32

标签: python google-cloud-storage

我正在使用rest api

将文件上传到Google云端存储

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

1 个答案:

答案 0 :(得分:3)

您正在调用的上传方法要求请求正文仅包含 您要上传的数据。这就是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)