脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 详解python上传文件和字符到PHP服务器

详解python上传文件和字符到PHP服务器

2020-12-20 00:47脚本之家 Python

本篇内容主要给大家介绍了在python中上传字符或者文件到PHP服务器的相关实现代码,如果你正好用得到,一起学习下。

很多朋友在留言区询问关于python上传文件字符到服务器的问题,现编针对这个给大家整理了一个解决办法。

上传简单的字符串

 
?
1
 
2
3
4
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 为上传的服务器地址

上传文件

 
?
1
 
2
3
4
5
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中第一个参数为图片的地址,第二个参数表示二进制文件写的权限,http://httpbin.org/post是服务器的地址

python post方式 上传文件到php服务器

看了网上很多代码,都没有说如何具体的使用poster,试了两天,终于成功了

通过python调用php实现了文件上传

与大家分享一下:

首先要通过pip安装poster(easy_install 也是一样的):

pip install poster

image.py

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!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服务器的代码实现的两种方式,如果大家还有更好的内容可以在下方留言给我们,一起交流一下。

延伸 · 阅读

精彩推荐