简体   繁体   中英

error uploading files with python request library to google cloud storage

I'm uploading a file to google cloud storage with the rest api

with curl it works ok

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]"

but with python requests post the file is uploaded corrupted

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)

The method of upload you are calling requires that the request body contain only the data you are uploading. This is what the curl --data-binary option does. However requests.post(files=BLAH) is multipart-encoding your data, which is not what you want. Instead you want to use the data parameter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM