Home > Backend Development > Python Tutorial > How to Send Files Using POST from a Python Script with Requests?

How to Send Files Using POST from a Python Script with Requests?

Linda Hamilton
Release: 2024-10-28 14:05:30
Original
539 people have browsed it

How to Send Files Using POST from a Python Script with Requests?

How to Send Files Using POST from a Python Script

Sending files using POST from a Python script is a crucial task in various applications. Fortunately, the Requests library provides an easy and efficient solution for this issue.

The following code demonstrates how to send a file named "report.xls" using POST:

<code class="python">import requests

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, we:

  1. Open the file "report.xls" in binary read mode using the open() function.
  2. Create a POST request using the requests.post() function, specifying the target URL and attaching the file using the files parameter.

The response from the server is displayed in the output, providing details about the uploaded file, including its name, size, and content type. This demonstrates that the file was successfully sent and received by the server.

Using Requests, sending files via POST from a Python script becomes a straightforward process, allowing developers to easily handle file uploads in their applications.

The above is the detailed content of How to Send Files Using POST from a Python Script with Requests?. 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