操作
- 新建一个Flask工程,在static文件夹下新建一个images文件夹
- templates文件夹下创建upload.html、upload_ok.hml文件
![项目结构](https://i-blog.csdnimg.cn/blog_migrate/0a804008e1ce834160e225c003afa6a9.png)
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
from datetime import timedelta
import os
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app.send_file_max_age_default = timedelta(seconds=1)
@app.route('/upload', methods=['POST', 'GET'])
def upload():
if request.method == 'POST':
f = request.files['file']
if not (f and allowed_file(f.filename)):
return jsonify({"error": 1001, "msg": "图片类型:png、PNG、jpg、JPG、bmp"})
basepath = os.path.dirname(__file__)
upload_path = os.path.join(basepath, 'static/images', secure_filename(f.filename))
f.save(upload_path)
return render_template('upload_ok.html')
return render_template('upload.html')
if __name__ == '__main__':
app.run(host="0.0.0.0")
upload.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask网页上传图片演示</title>
</head>
<body>
<form action="http://10.1.12.47:5000/upload" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<input type="submit" value="上传" class="button-new" style="margin-top:15px;"/>
</form>
</body>
</html>
upload_ok.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask网页上传图片演示结果页面</title>
</head>
<body>
<h1>上传成功</h1>
</body>
</html>
测试
- upload.html界面
![上传网页](https://i-blog.csdnimg.cn/blog_migrate/b55c30f937f6318214e0b07cacec4fec.jpeg)
- upload_ok.html界面
![上传成功](https://i-blog.csdnimg.cn/blog_migrate/0deb4bf99969e973e7dbe0c0839e9c87.jpeg)
- 服务器界面,图片保存成功
![图片保存成功](https://i-blog.csdnimg.cn/blog_migrate/eef8a640a2c48d866eaa040867b9e814.jpeg)
完整工程
- 已上传到github上,其中的FlaskServer就是其完整的代码。https://github.com/hrdhrdhrdhrd/okhttpFlaskDemo
- AndroidClient则是通过okhttp写的一个安卓app,并上传图片到FlaskServer服务器中,详情见另一篇文章,https://blog.csdn.net/qq_26906345/article/details/91045074