Flask 下载文件

app.py

# coding: utf-8

import os

from flask import Flask, views
from flask import send_from_directory, render_template, redirect, url_for
from flask import request

app = Flask(__name__)

download_path = r"./"

# 基于类
class Download(views.MethodView):
    def get(self):
        filename = request.args.get('file', None)
        if filename == None or os.path.isfile(os.path.join(download_path, filename)) != True:
            return redirect(url_for("index"))
        return send_from_directory(download_path, filename = filename, as_attachment = True)

class Index(views.MethodView):
    def get(self):
        return render_template('index.html', files = os.listdir(download_path))

app.add_url_rule("/get", view_func=Download.as_view("donwload"))
app.add_url_rule("/", view_func=Index.as_view("index"))

# 基于方法
# @app.route("/", methods = ["GET"])
# def index():
#     return render_template('index.html', files = os.listdir(download_path))

# @app.route("/get", methods = ["GET"])
# def get():
#     filename = request.args.get('file', None)
#     if filename == None or os.path.isfile(os.path.join(download_path, filename)) != True:
#         return redirect(url_for("index"))
#     return send_from_directory(download_path, filename = filename, as_attachment = True)

if __name__ == '__main__':
    app.run(host = "0.0.0.0", port = 8080)

templates/index.html

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

<head>
</head>

<body>
    <div>
        <ul>
            {% for file in files %}
                <li><a href="/get?file={{ file }}">{{ file }}</a></li>
            {% endfor %}
        </ul>
    </div>
</body>

</html>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页