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

命运对每个人都是一样的,不一样的是各自的努力和付出不同,付出的越多,努力的越多,得到的回报也越多,在你累的时候请看一下身边比你成功却还比你更努力的人,这样,你就会更有动力。

导读:本篇文章讲解 python使用Flask框架进行上传和下载文件,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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,
):

参数解析:

  • path_or_file:要发送的文件的路径,如果给出了相对路径,则相对于当前工作目录。或者,以二进制模式打开的类文件对象。确保将文件指针查找到数据的开头。
  • mimetype:为文件发送的MIME类型。如果没有提供,它将尝试从文件名检测它。
  • as_attachment:指示浏览器应该提供给保存文件而不是显示它。
  • download_name:浏览器保存文件时使用的默认名称。默认为传递的文件名。
  • conditional:基于请求头启用条件响应和范围响应。需要传递一个文件路径和“environ“。
  • etag:计算文件的etag,这需要传递一个文件路径。也可以是字符串来代替。
  • last_modified:发送文件的最后修改时间,单位为秒。如果没有提供,它将尝试从文件路径检测它。
  • max_age:客户端应该缓存文件多长时间,以秒为单位。如果设置,’ ‘ Cache-Control ‘ ‘将为’ ‘ public ‘ ‘,否则将为’ ‘ no-cache ‘ ‘以选择条件缓存。

注意:

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

示例代码:

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 文件下载_flask下载_liyinchi1988的博客-CSDN博客

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142769.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!