实现代码如下:
import os
from flask import flash, request, redirect, url_for, Flask, send_from_directory, render_template
from werkzeug.utils import secure_filename
from templates import *
"""
#send_from_directory 接口返回真实的文件
secure_filename() : 对上传的文件进行校验,
"""
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'uploads')
ALLOWD_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'sql'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
def allowed_file(filename):
return '.'in filename and filename.rsplit('.', 1)[1].lower() in ALLOWD_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('NO file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('no select file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
print(filename, 'secure_filename')
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file', filename=filename))
return render_template('upload_file.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
app.run(debug=True)
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件的上传</title>
</head>
<body>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=上传>
</form>
</body>
</html>