简单获取客户端文本
后端:
# -*-coding:utf-8 -*-
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=["POST"]) # 如果不写,默认是 GET 方式
def hello():
"""
methods:
GET: 参数写在地址URL上的. 但是推荐用 POST 方式。 因为容易泄密
POST:
如果传图片,必须是 POST
"""
print(request.form.get("name")) # GET传输方式 也可以定义 method=["GET"]
return "hello world"
if __name__ == '__main__':
app.run(debug=True)
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:5000/" method="post">
<input name="name" value="">
<input type="submit" value="submit">
</form>
</body>
</html>
接收图片
后端:
# -*-coding:utf-8 -*-
import io
from flask import Flask, request, jsonify
from PIL import Image
app = Flask(__name__)
@app.route('/', methods=["POST"]) # 如果不写,默认是 GET 方式
def hello():
"""
methods:
GET: 参数写在地址URL上的. 但是推荐用 POST 方式。 因为容易泄密
POST:
如果传图片,必须是 POST
REST规范:过去的数据用表单的格式,回来的数据用JSON格式
"""
name = request.form.get("name")
# 接收图片
file = request.files.get("file")
img_bytes = file.read() # 文件读出来, 字节码
img = Image.open(io.BytesIO(img_bytes))
img.save('img.jpg')
# img.show()
return jsonify({'name': name, 'filelen': len(img_bytes)})
if __name__ == '__main__':
app.run(debug=True)
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:5000/" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input name="name" value="Tony">
<input type="submit" value="提交">
</form>
</body>
</html>