Uploading files using the requests
library is very simple. Below is a complete example showing how to upload a file using requests
, including basic error handling.
File Upload Example
import requests
def upload_file(file_path, url):
"""Upload a file to the specified URL"""
try:
# Open the file and upload it
with open(file_path, 'rb') as file:
files = {'file': file} # Dictionary of file parameters
response = requests.post(url, files=files) # Send a POST request
# Check the response status
response.raise_for_status() # If the response status code is not 200-299, an exception will be thrown
# Return JSON response
return response.json() # Assume the server returns JSON format data
except requests.RequestException as e:
print(f'File upload failed: {e}')
except FileNotFoundError:
print('File not found, please check the path')
except Exception as e:
print(f'An error occurred: {e}')
if __name__ == '__main__':
# Replace with the actual file path and API address
file_path = 'example.txt' # The path of the file to upload
url = 'https://api.example.com/upload' # Upload target URL
upload_response = upload_file(file_path, url)
if upload_response:
print('Upload Successfully:', upload_response)