0

I would like to upload a file from URL using Python requests.post

Would anyone guide me how to convert a file URL into binary data (multipart/form-data) for upload?

I have tried with these code but it return failed.

file = requests.get(file_url, stream=True)
file_upload = {
            "name": file_name,
            "uploadfile": file.content 
            }
headers = {
            'Content-Type': 'multipart/form-data',
            'Accept': 'application/json'
          }
requests.post('{POST_URL}', files=file_upload, headers=headers)

POST_URL is external service and only support PDF file (string($binary)).

{
    "name": string
    "uploadfile": string($binary) 
}

Thank you so much.

2 Answers 2

1

As per python-requests documentation (Here), if you specify files parameter in requests.post, it will automatically set requests content-type as 'multipart/form-data'. So, you just need to omit the headers part from your post request as:

import requests

file = requests.get('{FILE_URL}', stream=True)

with open({TEMP_FILE}, 'wb') as f:
    for chunk in response.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)

binaryContent = open({TEMP_FILE}, 'rb')

a = requests.post('{POST_URL}', data={'key': binaryContent.read()})

Update: You can first try downloading your file locally and posting its binary data to your {POST_URL} service.

Sign up to request clarification or add additional context in comments.

9 Comments

Thank you so much for your comment, I tried to omit the content-type but I got the error 415 - UNSUPPORTED MEDIA TYPE
@グエントォ, I have updated my answer, please check if it solves your issue.
Unlucky me that it still not working. I tried with local file also.
{POST_URL} service return {'error': 'bad_request', 'message': 'invalid upload'}
If possible, can you give the {POST_URL} here for testing?
|
0

Here's a simple function that can appropriately send your file to any endpoint you want:

def upload_file(file_path, token):
"""Upload the file and return the response from the server."""
headers = {'Authorization': f'Bearer {token}'}
with open(file_path, "rb") as file:
    files = {'file': (os.path.basename(file_path), file, 'application/pdf')}
    response = requests.post(post_url, headers=headers, files=files)
response.raise_for_status()
return response

Python will automatically pick the multipart/form-data content type for you. All you need to do is supply the file correctly. Using the Authorization is optional, but I added it in case the API you want to post to requires one.

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.