简体   繁体   中英

Send variable as PDF file with requests.post in Python

I have a PDF file as a bytes variable in python

file = b'%PDF-1.4\\n1 0 obj\\n<<\\n/Title (\\xfe\\xff)\\n/Creator (\\xfe\\xff)...R\\n>>\\nstartxref\\n63581\\n%%EOF\\n'

And I want to send this file via requests.post

upload_file_request = requests.post(url, files={'file' : open(file, 'rb')}, headers=headers_json)

But I get encoding errors such as 'utf-8' codec can't decode byte 0xfe in position 28: invalid start by and others. What is the right way to do this?

UPDATE
Okay,so what I did was use tempfile to save my variable and then read it from there

    file = NamedTemporaryFile(delete=False)
    file_name = file.name
    file.write(doc_file)
    file.seek(0)

    upload_passport_file_request = requests.post(url,
                 files={"file": ("PDF", open(file_name, 'rb'), "application/pdf")},
                 headers=headers_turnkey)
   
    file.close()
    os.unlink(file_name)

Not the most beautiful solution but it works

You are posting a file with the name "file". That is your PDF content is the file name. You need to post data.

upload_file_request = requests.post(url, data=file)

See here how to do it right: https://www.w3schools.com/PYTHON/ref_requests_post.asp#:~:text=%20Python%20Requests%20post%20%28%29%20Method%20%201,certain%20HTTP%20authentication.%20A%20String%20or...%20More%20

https://www.w3schools.com/PYTHON/showpython.asp?filename=demo_requests_post

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