2

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)
4
  • how big is the file you are trying to upload? Commented Aug 29, 2017 at 21:33
  • a image of 11,2 kB Commented Aug 29, 2017 at 21:34
  • try files = {'media.jpeg': image_file.read()} Commented Aug 29, 2017 at 21:54
  • same error, with or without .read() Commented Aug 29, 2017 at 22:13

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.