很多朋友在留言區(qū)詢(xún)問(wèn)關(guān)于python上傳文件和字符到服務(wù)器的問(wèn)題,現(xiàn)編針對(duì)這個(gè)給大家整理了一個(gè)解決辦法。
上傳簡(jiǎn)單的字符串
def send_str_server(self):
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post",
data=payload)
介紹:payload 為鍵值對(duì)形式的數(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 為鍵值對(duì)形式的數(shù)據(jù),為post請(qǐng)求攜帶的數(shù)據(jù)
files 中的img表示的是php服務(wù)器中對(duì)圖片的過(guò)濾字段,open中第一個(gè)參數(shù)為圖片的地址,第二個(gè)參數(shù)表示二進(jìn)制文件寫(xiě)的權(quán)限,http://httpbin.org/post是服務(wù)器的地址
python post方式 上傳文件到php服務(wù)器
看了網(wǎng)上很多代碼,都沒(méi)有說(shuō)如何具體的使用poster,試了兩天,終于成功了
通過(guò)python調(diào)用php實(shí)現(xiàn)了文件上傳
與大家分享一下:
首先要通過(guò)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]可調(diào)用參數(shù) 例如 運(yùn)行 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 是一個(gè)生成器對(duì)象,返回編碼過(guò)后的參數(shù)
datagen, headers = multipart_encode({"myFile": f})
# 創(chuàng)建請(qǐng)求對(duì)象
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
----
以上就是小編親測(cè)的關(guān)于python上傳和文件和字符到PHP服務(wù)器的代碼實(shí)現(xiàn)的兩種方式,如果大家還有更好的內(nèi)容可以在下方留言給我們,一起交流一下。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

