如何在Python Sockets中接收和保存HTTP POST请求中的图片?
我刚开始学习Python中的套接字编程,想通过客户端发送一张图片,使用POST请求,并把这张图片保存在服务器上。
我觉得我已经把客户端的部分准备好了,但不太确定。
这是我的客户端代码:
import httplib
def printText(txt):
lines = txt.split('\n')
for line in lines:
print line.strip()
httpServ = httplib.HTTPConnection("127.0.0.1", 80)
httpServ.connect()
var = raw_input("Please enter a path of an image: ")
image = open(var, 'rb')
image_data = image.read()
image.close()
httpServ.request('POST', '/uplaod', image_data)
response = httpServ.getresponse()
if response.status == httplib.OK:
print "Output from CGI request"
printText(response.read())
httpServ.close()
我想问的是,服务器端应该怎么接收这张图片,然后又该怎么把接收到的图片保存在某个路径下。
1 个回答
0
我个人在想要快速搭建一个简单的网络服务时,会使用Bottle这个库。就像下面这样:
import bottle
app=bottle.app()
@app.post('/upload')
def doUpload():
upload = request.files['upload']
upload.save('filename')
app.run()
显然,这个代码需要根据你的托管需求进行一些调整。