0


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

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 ' '以选择条件缓存。

注意:

示例代码:

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博客

标签: python flask send_file

本文转载自: https://blog.csdn.net/weixin_44799217/article/details/128962213
版权归原作者 IT之一小佬 所有, 如有侵权,请联系我们删除。

“python使用Flask框架进行上传和下载文件”的评论:

还没有评论