Python: 3.6.10
Flask: 1.1.2
目录结构
- index.py
- templates
- index.html
- test.png
前端代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Upload Example</title>
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>Upload Test</h1>
<form method="POST" action="http://127.0.0.1:5000/upload" enctype="multipart/form-data">
<label>Select a file:</label><br>
<input type="file" id="myFile" name="myFile" />
<input type="text" id="myText" name="myText" />
<input type="submit" />
</form>
</body>
</html>
服务端代码
from flask import render_template, Flask, request, jsonify
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
data = request.form
file = request.files['myFile']
result = {'input': data['myText'], 'file': secure_filename(file.filename)}
if file:
file.save(r'C:/' + secure_filename(file.filename))
return jsonify(result)
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=5000)