把当前文件夹下的所有文件夹和文件列出来,允许点击返回上层目录,允许点击文件夹进入下级目录并显示此文件夹内容
允许点击文件进行下载
from flask import Flask, render_template, send_file, request, redirect, url_for
import os
app = 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/' )
def download_file(file_name):
return send_file(file_name, as_attachment=True)
@app.route('/show_folder/' )
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/' )
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 Viewertitle>
head>
<body>
<h1>Folder Viewerh1>
{% 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 selectedp>
{% endif %}
body>
html>
Bug:
目前在子目录没办法下载
问题原因:
{{ filename }}