flask文件夹列表前文修订版

2023-12-28 05:44:41

书接上文:
https://blog.csdn.net/weixin_44517278/article/details/135228805

本文的代码和HTML模板已经修改了上文的问题,目前可以做到正常的上传,返回上层目录,下载

from flask import Flask, render_template, send_file, request, redirect, url_for
import os

app = Flask(__name__)

@app.template_filter('basename')
def basename_filter(value):
    return os.path.basename(value)

@app.route('/')
def index():
    files, folder_names, folder_name = getfile()
    return render_template('index.html', files=files, folder_names=folder_names, folder_name=folder_name)

@app.route('/download/<file_name>')
def download_file(file_name):
    file_name = os.path.normpath(file_name)  # 替换windows环境下出现的双斜杠 \\ 为 /
    return send_file(file_name, as_attachment=True)

@app.route('/show_folder/<folder_name>')
def show_folder(folder_name):
    files, folder_names, folder_name = getfile(folder_name)
    return render_template('index.html', files=files, folder_names=folder_names, folder_name=folder_name)

# 这里是返回上一级的目录
@app.route('/return_folder/<folder_name>')
def return_folder(folder_name):
    refolder = folder_name
    # 抓完全体的路径
    full_path = os.path.join(os.getcwd(), refolder)
    # 遍历指定(这里是当前)目录下的所有文件和文件夹
    for root, dirs, files in os.walk(os.getcwd(), topdown=True):
        # 遍历文件夹
        for dir in dirs:
            # 当此文件夹的完整路径等于传入文件夹的所有路径的时候,root就是这个文件夹的上级目录
            if os.path.join(root, dir) == full_path:
                # 用这个抓出来上级目录的相对路径,这条命令的作用就是抓相对路径,起始位置为start定义的位置
                folder_name = os.path.relpath(root, start=os.getcwd())
                # 两个目录相同的时候,相对路径就是 . , 当相对路径是这个,代表到根目录了,就不提供返回按钮了
                if folder_name == ".":
                    folder_name = ""
                files, folder_names, folder_name = getfile(folder_name)
                return render_template('index.html', files=files, folder_names=folder_names, folder_name=folder_name)

def getfile(folder_name=""):
    files = []
    folder_names = []
    fileList = os.listdir(os.path.join(os.getcwd(), folder_name))
    for file in fileList:
        file = os.path.join(folder_name, file)
        file = os.path.normpath(file)  # 替换windows环境下出现的双斜杠 \\ 为 /
        if os.path.isfile(file):
            files.append(file)
        else:
            folder_names.append(file)
    return files, folder_names, folder_name

@app.route('/upload', methods=['POST'])
def upload_file():
    # 接受HTML返回的需要下载的文件名
    file = request.files['file']
    # 接受HTML返回的folder_name的值(我这里folder_name是相对路径值)
    folder_name = request.form['folder_name']
    # 这里指定文件上传目录,实现选到那个路径下就上传文件到那个文件夹下
    UPLOAD_FOLDER = folder_name  
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    # 检查是否有文件被上传
    if 'file' not in request.files:
        return 'No file part'
    file = request.files['file']

    # 如果用户没有选择文件,浏览器会发送一个空的文件名
    if file.filename == '':
        return 'No selected file'

    # 保存文件到指定目录
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    files, folder_names, folder_name = getfile(folder_name)
    return render_template('index.html', files=files, folder_names=folder_names, folder_name=folder_name)


if __name__ == '__main__':
    app.run(debug=True)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Folder Viewer</title>
</head>
<body>

<h1>文件上传下载列表</h1>
{% if folder_name == "" or folder_name %}
    {% if folder_name == "" %}
    <p>当前路径:</p>
    {% else %}
        <p>当前路径:</p>
            <li><a href="{{ url_for('return_folder', folder_name=folder_name) }}">返回:{{ folder_name|basename }}</a></li>
    {% endif %}
    <form method="post" enctype="multipart/form-data" action="/upload">
        <input type="file" name="file">
        <input type="hidden" name="folder_name" value="{{ folder_name }}">
        <input type="submit" value="Upload">
    </form>
    <ul>
        <h2>文件:</h2>
        {% for filename in files %}
            <li><a href="{{ url_for('download_file', file_name=filename) }}" download>{{ filename|basename }}</a></li>
        {% endfor %}
        <h2>文件夹:</h2>
        {% for foldername in folder_names %}
            <li><a href="{{ url_for('show_folder', folder_name=foldername) }}">{{ foldername|basename }}</a></li>
        {% endfor %}
    </ul>
{% else %}
    <p>No folder selected</p>
{% endif %}


</body>
</html>


文章来源:https://blog.csdn.net/weixin_44517278/article/details/135202886
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。