[英]Send variable as PDF file with requests.post in Python
I have a PDF file as a bytes variable in python我有一个 PDF 文件作为 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我想通过 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.但是我收到编码错误,例如
'utf-8' codec can't decode byte 0xfe in position 28: invalid start by
等。 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好的,所以我所做的是使用
tempfile
来保存我的变量,然后从那里读取它
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)
You are posting a file with the name "file".您正在发布一个名为“file”的文件。 That is your PDF content is the file name.
那就是你的PDF内容就是文件名。 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/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 https://www.w3schools.com/PYTHON/showpython.asp?filename=demo_requests_post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.