python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python的Flask框架上传下载

使用python的Flask框架进行上传和下载文件详解

作者:IT之一小佬

这篇文章主要介绍了使用python的Flask框架进行上传和下载文件详解,Flask是一个使用Pyhton编写的轻量级Web应用框架,工具包采用Werkzeug,模板引擎则使用Jinja2,是目前十分流行的web框架,需要的朋友可以参考下

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/<string:user_name>', 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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

到此这篇关于使用python的Flask框架进行上传和下载文件详解的文章就介绍到这了,更多相关python的Flask框架上传下载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文