用 Python + Requests 实现一个简单的文件上传工具(详细教程)
·
本文将带你从零编写一个可以上传本地文件到服务器的 Python 脚本。
全文不到 50 行代码,却足够轻巧实用,还能扩展成自己的文件上传 GUI 工具。
🧰 一、环境准备
在开始之前,请确保你的电脑已安装:
-
Python 3.x
-
requests库(没有的话可使用 pip 安装)
pip install requests
📦 二、完整代码
下面是一个完整的文件上传脚本,可以直接运行 👇
import requests
def upload_file(file_path, server_url):
"""上传本地文件到服务器"""
try:
# 打开要上传的文件
with open(file_path, 'rb') as f:
files = {'file': (file_path, f)}
print(f"正在上传文件 {file_path} 到 {server_url} ...")
response = requests.post(server_url, files=files)
# 打印服务器返回结果
if response.status_code == 200:
print("✅ 上传成功!服务器返回:")
print(response.text)
else:
print(f"❌ 上传失败,状态码:{response.status_code}")
print(response.text)
except Exception as e:
print(f"⚠️ 上传过程中出错:{e}")
if __name__ == "__main__":
# 手动输入服务器URL和本地文件路径
server_ip = input("请输入服务器IP地址,例如 http://192.168.1.101:5000 : ").strip()
upload_url = server_ip.rstrip('/') + '/upload' # 拼接成完整接口
file_path = input("请输入要上传的本地文件完整路径: ").strip()
upload_file(file_path, upload_url)
🧠 三、代码详解
1️⃣ 导入模块
import requests
requests 是 Python 最流行的 HTTP 网络请求库,用于发送 GET / POST 请求。
2️⃣ 定义上传函数
def upload_file(file_path, server_url):
这是上传核心逻辑的函数。它完成以下工作:
-
打开本地文件;
-
向服务器发起 POST 请求;
-
根据状态码判断上传是否成功;
-
捕获异常,防止程序崩溃。
3️⃣ 发送 POST 请求
files = {'file': (file_path, f)} response = requests.post(server_url, files=files)
这两行代码使用表单格式(multipart/form-data)上传文件。
服务器可通过 request.files['file'] 接收文件(Flask 等框架常见)。
4️⃣ 判断上传结果
if response.status_code == 200:
print("✅ 上传成功!服务器返回:")
print(response.text)
else:
print(f"❌ 上传失败,状态码:{response.status_code}")
-
状态码
200表示服务器返回成功。 -
其它状态码表示失败,如 400、403、500 等。
-
你也可以根据返回 JSON 的内容进一步判断。
5️⃣ 主程序入口
if __name__ == "__main__":
程序运行后,会让用户手动输入:
-
服务器地址(如
http://192.168.1.101:5000) -
要上传的本地文件路径(如
D:\test.txt)
示例输入:
请输入服务器IP地址,例如 http://192.168.1.101:5000 : http://192.168.1.101:5000
请输入要上传的本地文件完整路径: C:\Users\test\Desktop\demo.txt
⚙️ 四、运行结果
示例输出:
请输入服务器IP地址,例如 http://192.168.1.101:5000 :
http://127.0.0.1:5000 请输入要上传的本地文件完整路径: D:\demo.txt
正在上传文件 D:\demo.txt 到 http://127.0.0.1:5000/upload ...
✅ 上传成功!服务器返回:
文件 demo.txt 上传成功!
✅ 五、总结
本文展示了如何用 Python + Requests 实现最简洁的文件上传工具。
关键要点:
-
使用
requests.post()+files参数; -
正确处理异常;
-
保证服务器端
/upload接口可用。
更多推荐


所有评论(0)