send_file()函数:
def send_file(
path_or_file: t.Union[os.PathLike, str, t.BinaryIO],
mimetype: t.Optional[str] = None,
as_attachment: bool = False,
download_name: t.Optional[str] = None,
attachment_filename: t.Optional[str] = None,
conditional: bool = True,
etag: t.Union[bool, str] = True,
add_etags: t.Optional[bool] = None,
last_modified: t.Optional[t.Union[datetime, int, float]] = None,
max_age: t.Optional[
t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
] = None,
cache_timeout: t.Optional[int] = None,
):
参数解析:
注意:
示例代码:
import os
from flask import Flask, send_file, request, render_template, redirect
from werkzeug.utils import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = 'media' # 注意:要提前在根目录下新建media文件,否则会报错
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 判断上传的文件是否是允许的后缀
def allowed_file(filename):
return "." in filename and filename.rsplit('.', 1)[1].lower() in set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
@app.route('/')
def index():
return "hello world!"
@app.route('/generate_file')
def generate_file():
with open('./new_file.txt', 'w', encoding='utf-8') as f:
f.write('我是new_file.txt文件!')
return "<./new_file.txt>文件已经生成!"
@app.route('/download')
def download():
return send_file('./new_file.txt', as_attachment=True)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
else:
if "file" not in request.files:
return redirect(request.url)
file = request.files.get('file') # 获取文件
# 上传空文件(无文件)
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
if not os.path.exists(f'./templates/{UPLOAD_FOLDER}'):
os.mkdir(f'./templates/{UPLOAD_FOLDER}')
filename = secure_filename(file.filename) # 用这个函数确定文件名称是否是安全 (注意:中文不能识别)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # 保存文件
return "上传文件成功!"
if __name__ == '__main__':
app.run()
下载和上传路径中可以添加用户身份验证:
import os
from flask import Flask, send_file, request, render_template, redirect
from werkzeug.utils import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = 'media' # 注意:要提前在根目录下新建media文件,否则会报错
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
allow_users = ['dgw', 'super_user']
# 判断上传的文件是否是允许的后缀
def allowed_file(filename):
return "." in filename and filename.rsplit('.', 1)[1].lower() in set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
@app.route('/')
def index():
return "hello world!"
@app.route('/generate_file')
def generate_file():
with open('./new_file.txt', 'w', encoding='utf-8') as f:
f.write('我是new_file.txt文件!')
return "<./new_file.txt>文件已经生成!"
@app.route('/download')
def download():
user_name = request.args.get('user_name')
if not user_name:
return "你没有权限下载文件!"
if user_name and user_name not in allow_users:
return "你没有权限下载文件!"
return send_file('./new_file.txt', as_attachment=True)
@app.route('/upload/', methods=['GET', 'POST'])
def upload(user_name):
if request.method == 'GET':
if user_name not in allow_users:
return "您没有权限访问此页面!"
return render_template('upload.html')
else:
if user_name not in allow_users:
return "您没有权限访问此页面!"
if "file" not in request.files:
return redirect(request.url)
file = request.files.get('file') # 获取文件
# 上传空文件(无文件)
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
if not os.path.exists(f'./templates/{UPLOAD_FOLDER}'):
os.mkdir(f'./templates/{UPLOAD_FOLDER}')
filename = secure_filename(file.filename) # 用这个函数确定文件名称是否是安全 (注意:中文不能识别)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # 保存文件
return "上传文件成功!"
if __name__ == '__main__':
app.run()
附录:
upload.html
Upload
参考博文:
Python Flask 文件下载_flask下载_liyinchi1988的博客-CSDN博客