把当前文件夹下的所有文件夹和文件列出来,允许点击返回上层目录,允许点击文件夹进入下级目录并显示此文件夹内容
允许点击文件进行下载
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:
目前在子目录没办法下载
问题原因:
%7B%20url_for('download_file',%20file_name=filename)%20%7D%7D" download>{{ filename }}
这里的定义的路径不支持下载子目录的文件,需要优化 file_name,把子目录的路径包含进去
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
相关推荐: 盘点Java集合(容器)概览,Collection和Map在开发中谁用的最多?
写在开头 在Java的世界里万物皆对象。但我认为是万物皆数据,世界由各种各样数据构建起来,我们通过程序去实现数据的增删改查、转入转出、加减乘除等等,不同语言的实现方式殊途同归。由此可见,数据对于程序语言的重要性。 这段话是在写数据类型那篇博客时说的,当时是为了…