国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解python上傳文件和字符到PHP服務(wù)器

2020-02-16 10:50:58
字體:
供稿:網(wǎng)友

很多朋友在留言區(qū)詢問關(guān)于python上傳文件和字符到服務(wù)器的問題,現(xiàn)編針對這個給大家整理了一個解決辦法。

上傳簡單的字符串

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

介紹:payload 為鍵值對形式的數(shù)據(jù),在服務(wù)器的數(shù)據(jù)的顯示為

key1=value1&key2=value2

http://httpbin.org/post 為上傳的服務(wù)器地址

上傳文件

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 為鍵值對形式的數(shù)據(jù),為post請求攜帶的數(shù)據(jù)

files 中的img表示的是php服務(wù)器中對圖片的過濾字段,open中第一個參數(shù)為圖片的地址,第二個參數(shù)表示二進(jìn)制文件寫的權(quán)限,http://httpbin.org/post是服務(wù)器的地址

python post方式 上傳文件到php服務(wù)器

看了網(wǎng)上很多代碼,都沒有說如何具體的使用poster,試了兩天,終于成功了

通過python調(diào)用php實現(xiàn)了文件上傳

與大家分享一下:

首先要通過pip安裝poster(easy_install 也是一樣的):

pip install poster

image.py

#!usr/bin/python# image.py# -*- coding=utf-8 -*- from poster.encode import multipart_encodeimport urllib2import sysfrom urllib2 import Request, urlopen, URLError, HTTPErrorfrom poster.encode import multipart_encodefrom poster.streaminghttp import register_openersregister_openers()f=open(“C:/Users/User/Pictures/Saved Pictures/test1.jpg”, "rb")#f=open(sys.argv[1], "rb") 使用sys.argv[1]可調(diào)用參數(shù) 例如 運行 python image.py C:/Users/User/Pictures/Saved Pictures/test1.jpg #可將test1.jpg作為參數(shù)傳入image.py#"C:/Users/User/Pictures/Saved Pictures/vedio5.jpg"# headers 包含必須的 Content-Type 和 Content-Length# datagen 是一個生成器對象,返回編碼過后的參數(shù)datagen, headers = multipart_encode({"myFile": f})# 創(chuàng)建請求對象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.reasonprint e.code-----upload_image.php----<?phpecho $_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'];//將文件傳到服務(wù)器根目錄的 upload 文件夾中if(move_uploaded_file($tmpname,$_SERVER['DOCUMENT_ROOT']."/upload/".$filename)){echo "upload image succeed";}else{echo "upload image failed";}}?>            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 丹东市| 辽源市| 崇信县| 武强县| 如皋市| 万全县| 衡水市| 永胜县| 三明市| 鞍山市| 深泽县| 龙川县| 迁西县| 饶河县| 普洱| 彩票| 镶黄旗| 苏州市| 武宁县| 岳池县| 上蔡县| 日土县| 荃湾区| 广元市| 临江市| 河池市| 长乐市| 化德县| 钟山县| 修水县| 彭阳县| 上蔡县| 昭平县| 台江县| 岢岚县| 福海县| 威信县| 天门市| 全南县| 台北市| 淅川县|