本文主要是介绍flask文件夹列表改进版--Bug追踪,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
把当前文件夹下的所有文件夹和文件列出来,允许点击返回上层目录,允许点击文件夹进入下级目录并显示此文件夹内容
允许点击文件进行下载
from flask import Flask, render_template, send_file, request, redirect, url_for
import osapp = Flask(__name__)@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):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):for root, dirs, files in os.walk(os.getcwd(), topdown=True):for dir in dirs:if folder_name == dir: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:if os.path.isfile(file):files.append(file)else:folder_names.append(file)return files, folder_names, folder_name
<!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>Folder Viewer</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 }}</a></li>{% endif %}<form method="post" enctype="multipart/form-data"><input type="file" name="file"><input type="submit" value="Upload"></form><ul>{% for filename in files %}<li><a href="{{ url_for('download_file', file_name=filename) }}" download>{{ filename }}</a></li>{% endfor %}{% for foldername in folder_names %}<li><a href="{{ url_for('show_folder', folder_name=foldername) }}">{{ foldername }}</a></li>{% endfor %}</ul>
{% else %}<p>No folder selected</p>
{% endif %}</body>
</html>
效果:
主页面:
子目录:
点击返回可以返回上层目录:
Bug:
目前在子目录没办法下载
问题原因:
<li><a href="{{ url_for('download_file', file_name=filename) }}" download>{{ filename }}</a></li>
这里的定义的路径不支持下载子目录的文件,需要优化 file_name,把子目录的路径包含进去
这篇关于flask文件夹列表改进版--Bug追踪的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!