加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 07:49:55 所属栏目:Python 来源:网络整理
导读:很多朋友在留言区询问关于python上传文件和字符到服务器的问题,现编针对这个给大家整理了一个解决办法。 上传简单的字符串 def send_str_server(self):payload = {'key1': 'value1','key2': 'value2'}r = requests.post("http://httpbin.org/post",data=pay

很多朋友在留言区询问关于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中第一个参数为图片的地址,第二个参数表示二进制文件写的权限,http://httpbin.org/post是服务器的地址

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

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

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

与大家分享一下:

首先要通过pip安装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服务器的代码实现的两种方式,如果大家还有更好的内容可以在下方留言给我们,一起交流一下。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读