Home > Backend Development > Python Tutorial > How do I send a file using POST from a Python script?

How do I send a file using POST from a Python script?

Barbara Streisand
Release: 2024-10-29 07:06:31
Original
448 people have browsed it

How do I send a file using POST from a Python script?

Sending Files Using POST from a Python Script

Sending files using the POST method in Python can be straightforward using the Requests library. To accomplish this, follow these steps:

Using the Requests Library

From the Requests documentation (https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file), the following code snippet demonstrates how to send a file using POST:

<code class="python">with open('report.xls', 'rb') as f:
    r = requests.post('http://httpbin.org/post', files={'report.xls': f})</code>
Copy after login

In this code:

  • open('report.xls', 'rb') as f opens the file report.xls in binary read mode.
  • requests.post('http://httpbin.org/post', files={'report.xls': f}) sends a POST request to the specified URL with the file as part of the request body.

Verifying the File Upload

To confirm that the file was uploaded successfully, you can print the response from the POST request. For example:

<code class="python">>>> print(r.text)</code>
Copy after login

The above is the detailed content of How do I send a file using POST from a Python script?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template