Python向PHP服务器上传文件与数据的两种实现方案

Elena
Elena
发布时间:2026-10-13| 4人浏览过
原创

本文详细解析了Python向PHP服务器上传数据与文件的两种核心方式。第一种利用requests库发送键值对字符串,适用于简单数据传输;第二种通过poster库构建multipart/form-data请求实现文件上传,涵盖安装配置、代码逻辑及PHP后端处理流程,提供完整可运行的代码示例。

针对许多开发者在互动区咨询的Python向服务器传输文件及字符数据的需求,本文整理并提供了具体的解决方案。

上传简单的字符串数据

def send_str_server(self):
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", 
data=payload)

方法说明:使用payload参数传递键值对形式的数据,服务器端接收到的数据显示格式为

key1=value1&key2=value2

目标服务器地址示例为:http://httpbin.org/post

上传文件

def send_image_server(self):
data = {"k1" : "v1"} 
files = {"img" : open("test.png", "rb")} 
r = requests.post("http://httpbin.org/post", data,
files=files)

方法说明:data参数用于传递键值对形式的数据,作为POST请求携带的主体内容。

files参数中的img对应PHP服务器端处理图片的过滤字段名;open函数的第一个参数指定图片文件路径,第二个参数"rb"表示以二进制读取模式打开文件;目标服务器地址示例为http://httpbin.org/post。

使用Python POST方式将文件上传至PHP服务器

参考网络上的许多代码示例,往往缺乏关于如何具体使用poster库的详细步骤。经过两天的测试与调试,最终成功实现了功能。

通过Python调用PHP接口实现了文件上传功能。

具体实现步骤分享如下:

首先需要安装poster库(使用easy_install方式同样可行):

pip install poster

image.py脚本示例

#!usr/bin/python
# image.py
# -*- coding=utf-8 -*- 
from poster.encode import multipart_encode
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

register_openers()
f=open(“C:/Users/User/Pictures/Saved Pictures/test1.jpg”, "rb")
#f=open(sys.argv[1], "rb") 使用sys.argv[1]可调用参数 例如 运行 python image.py C:/Users/User/Pictures/Saved Pictures/test1.jpg 
#可将test1.jpg作为参数传入image.py
#"C:/Users/User/Pictures/Saved Pictures/vedio5.jpg"
# headers 包含必须的 Content-Type 和 Content-Length
# datagen 是一个生成器对象,返回编码过后的参数
datagen, headers = multipart_encode({"myFile": f})
# 创建请求对象
request = urllib2.Request("http://localhost/upload_image/upload_image.php", datagen, headers)
try:
response = urllib2.urlopen(request)
print response.read()

except URLError,e:
print e.reason
print e.code
-----

upload_image.php

----
<?php
echo $_FILES['myFile']['name'];
if (isset($_FILES['myFile'])) 
{
$names = $_FILES["myFile"]['name'];
$arr = explode('.', $names);
$name = $arr[0]; //图片名称
$date = date('Y-m-d H:i:s'); //上传日期
$fp= fopen($_FILES['myFile']['tmp_name'], 'rb');
$type = $_FILES['myFile']['type'];
$filename = $_FILES['myFile']['name'];
$tmpname = $_FILES['myFile']['tmp_name'];
//将文件传到服务器根目录的 upload 文件夹中
if(move_uploaded_file($tmpname,$_SERVER['DOCUMENT_ROOT']."/upload/".$filename)){
echo "upload image succeed";
}else{
echo "upload image failed";
}
}
?>

以上为经过实测的Python向PHP服务器上传文件及字符数据的两种代码实现方式。如果您有更优化的方案,欢迎在下方留言交流。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。