很多朋友在留言區詢問關于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服務器的代碼實現的兩種方式,如果大家還有更好的內容可以在下方留言給我們,一起交流一下。