# 导入必要的库
from flask import Flask, request, redirect, url_for, flash
import os
# 创建Flask应用
app = Flask(__name__)
app.secret_key = 'supersecretkey' # 设置密钥用于flash消息
# 设置上传文件保存的目录
UPLOAD_FOLDER = './uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 检查文件扩展名是否允许
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# 处理文件上传的路由
@app.route('/upload', 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']
# 如果用户没有选择文件,浏览器也会提交一个空的part没有filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename) # 确保文件名安全
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file', filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
# 启动应用
if __name__ == '__main__':
app.run(debug=True)
这段代码使用了Flask框架来实现文件上传功能。具体步骤如下:
flash
)。allowed_file
来检查文件扩展名是否在允许的列表中。/upload
,当用户通过表单上传文件时,服务器会检查文件是否合法,并保存到指定目录。这个示例展示了如何使用Flask框架实现文件上传的基本功能。
上一篇:python的split用法
下一篇:python hex转字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站