HTML,包含一个text类型文本框和file类型上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>拍照</title>
</head>
<body>
<h1>拍照上传演示</h1>
<form id="upForm" enctype="multipart/form-data" method="POST">
<p>
<span>用户名:</span>
<input type="text" name="username" />
</p>
<input name="pic" type="file" accept="image/*" capture="camera" />
<a onclick="upload()">上传</a>
</form>
<img id="image" width="300" height="200" />
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
function upload() {
var data = new FormData($("#upForm")[0]);
$.ajax({
url: '/do',
method: 'POST',
data: data,
processData: false,
contentType: false,
cache: false,
success: function (ret) {
console.log(ret)
}
})
}
</script>
</html>
Python
import os
from flask import Flask, render_template, request, jsonify
from werkzeug import secure_filename
TEMPLATES_AUTO_RELOAD = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['JSON_AS_ASCII'] = False
PIC_FOLDER = os.path.join(app.root_path, 'upload_pic')
@app.route('/', methods=['GET'])
def hello():
return render_template('index.html')
@app.route('/do', methods=['POST'])
def do():
data = request.form
file = request.files['pic']
result = {'username': data['username']}
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(PIC_FOLDER, filename))
result['pic'] = filename
return jsonify(result)
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=8000)