web服务器向客户端发送文件
Web服务器读取一个文件的二进制数据,把这组二进制数据发送个客户端,服务器发送给客户端的HTML文档的本质也是二进制。客户端使用以下代码读文件
response = urllib.request.urlopen(url + "?" + urllib.parse.quote(fileName))
data = response.read()
server.py
import flask app = flask.Flask(__name__)@app.route('/', methods=['GET','POST']) def index():if not "fileName" in flask.request.values:s = "test.jpg"return selse:fileName = flask.request.values.get("fileName")f = open(fileName, "rb")data = f.read()f.close()return dataif __name__ == '__main__':app.run()
clent.py
import urllib.request import urllib.parseurl = "http://127.0.0.1:5000" response = urllib.request.urlopen(url) data = response.read() fileName = data.decode('utf-8') response = urllib.request.urlopen(url + "?" + urllib.parse.quote(fileName)) data = response.read() f = open("dowmload" + fileName, "wb") f.write(data) f.close() print(fileName, len(data))
静态文件夹文件下载
server.py
import flask app = flask.Flask(__name__)@app.route('/', methods=['GET','POST']) def index():return "Image"if __name__ == '__main__':app.run()
client.py
import urllib.request import urllib.parseurl = "http://127.0.0.1:5000/static/test.jpg" response = urllib.request.urlopen(url) data = response.read() f = open("dowmload test.jpg", "wb") f.write(data) f.close() print("downloaded", len(data), "bytes")