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
Barbara StreisandOriginal
2024-10-29 07:06:31458browse

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>

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>

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!

Statement:
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