其他分享
首页 > 其他分享> > falsk静态多层文件展示+下载

falsk静态多层文件展示+下载

作者:互联网

有偿求助,代码如下,主页展示和下载功能正常。但是只要把首页路由改了,比如改成“/1”,就只有首页可以用,点文件夹进入下层文件夹就报错。

【flask代码】

from flask import Flask
from flask import request
from flask import render_template, send_from_directory
import os
import time
app = Flask(__name__)
# 这里是预先将值存储在系统环境变量中了
app.secret_key = 'QWEaRdskjgkjgads3TYUdI2fdgfsgdafdsafdOPdkjgkjgdskjgkjgaf1234ffdfdasa56fdakjgkjgkfaaa'
DEFAULT_PATH = 'D:/'
current_path = ''

# 获取文件信息的函数
def get_files_data(path):
    """
    获取指定路径下的所有文件、文件夹的信息
    """
    global current_path
    files = []

    for the_name in os.listdir(path):
        # 拼接路径
        file_path = path+"/"+the_name

        # 判断是文件夹还是文件
        if os.path.isfile(file_path):
            the_type = 'file'

        else:
            the_type = 'dir'

        name = the_name

        size = os.path.getsize(file_path)
        size = file_size_fomat(size, the_type)
        # 创建时间
        ctime = time.localtime(os.path.getctime(file_path))

        # 封装成字典形式追加给 files 列表
        files.append({
            "name": name,
            "size": size,
            # 拼接年月日信息
            "ctime": "{}/{}/{}".format(ctime.tm_year, ctime.tm_mon, ctime.tm_mday),
            "type": the_type
        })
    # 更新当前路径
    current_path = path
    return files


def file_size_fomat(size, the_type):
    """
    文件大小格式化,携带单位
    """
    if the_type == 'dir':
        return '<DIR>'
    else:
        if size < 1024:
            return '%i' % size + ' B'
        elif 1024 < size <= 1048576:
            return '%.1f' % float(size/1024) + ' KB'
        elif 1048576 < size <= 1073741824:
            return '%.1f' % float(size/1048576) + ' MB'
        elif 1073741824 < size <= 1099511627776:
            return '%.1f' % float(size/1073741824) + ' GB'


def get_current_path():
    return current_path

@app.route('/', methods=['GET', 'POST'])
def jingshijiaoyu():
    if request.method == 'GET':
        return render_template("jingshijiaoyu.html",
                               data={
                                   "files": get_files_data(DEFAULT_PATH),
                                   "currentPath": DEFAULT_PATH,
                               })

    else:
        # POST 请求下获取传递的路径信息,并返回相应数据
        if request.form.get('pathText'):
            path_text = request.form.get('pathText')
            return render_template("jingshijiaoyu.html",
                                   data={
                                       "files": get_files_data(path_text),
                                       "currentPath": get_current_path(),
                                   })

@app.route("/download_file/<filename>")
def file_content(filename):
    # 若文件存在
    if filename in os.listdir(get_current_path()):
        # 发送文件 参数:路径,文件名

        return send_from_directory(get_current_path(), filename)
    else:
        return render_template("download_error.html", filename=filename)



if __name__ == '__main__':
    # 监听在所有 IP 地址上
    app.run()

【html文件代码】

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="Cache-Control" content="no-cache" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />
  <title>flask 文件共享</title>
  <link rel="stylesheet" href="../static/css/jingshijiaoyu.min.css">
  <script src="../static/js/jingshijiaoyu.min.js"></script>
</head>

<body>
  <div class="all-container">
    <h1>文件共享</h1>
    <div class="drivers-container">
      根目录:
      {% for driver in data.drivers %}
      <a href="javascript:;" location="{{driver}}" style="color:#66ccff">{{driver}}</a>
      {% endfor %}
      <h3 class="currentPath">当前路径:<span>{{data.currentPath}}</span></h3>
    </div>
    <button class="to-lastPath" onclick="window.history.back()">&nbsp;←&nbsp;&nbsp;上级目录</button>
    <table class="files-table">
      <tr>
        <!-- 表头 -->
        <td class="td-name">文件或文件夹</td>
        <td class="td-size">大小</td>
        <td class="td-ctime">创建日期</td>
      </tr>
      <!-- 将传上来的files进行遍历 输出HTML标签 -->
      {% for file in data.files %}
      <tr type="{{file.type}}">
        <td class="td-name {{file.type}}"><a href="/download_file/{{file.name}}"
            dirname="{{file.name}}">{{file.name}}</a></td>
        <td class="td-size">{{file.size}}</td>
        <td class="td-ctime">{{file.ctime}}</td>
      </tr>
      {% endfor %}
    </table>
    <form action="/" method="POST" style="display: none;" id="pathForm">
      <input type="text" name="pathText" value>
      <input type="submit">
    </form>
    <section class="flash-tablet" style="display: none;">
      <div class="inner-container">
        <div class="drivers-container">
          根目录:
          {% for driver in data.drivers %}
          <a href="javascript:;" location="{{driver}}" style="color:black">{{driver}}</a>
          {% endfor %}
          <h3 class="currentPath">当前路径:<span>{{data.currentPath}}</span></h3>
        </div>
        <button class="to-lastPath" onclick="window.history.back()">&nbsp;←&nbsp;&nbsp;上级目录</button>
        <button id="to-top">返回顶部</button>
      </div>
    </section>
  </div>
</body>

</html>

标签:__,name,静态,falsk,多层,file,path,type,size
来源: https://blog.csdn.net/ygyg123123/article/details/121644842