EdgarAlejandro
EdgarAlejandro

Reputation: 367

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)

Upvotes: 2

Views: 1165

Answers (1)

David
David

Reputation: 9731

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)

Upvotes: 4

Related Questions