Flask预览或下载文件

功能区
 taochengwei   开发  flask   2017-07-11 16:14   百度主动推送失败
正文区

flask版本0.10.1

经测试,可以下载含有中文文件,预览txt、sh、py等(需自定义)文本文件,其他类型直接下载。

# -*- coding: utf-8 -*-


import os.path
from flask import Flask, request, make_response, send_from_directory

app = Flask(__name__)

@app.route("/download/")
def download():
    """ 下载附件、预览文本文件
    :catalog(str):  下载分类(子)目录,比如attachment、script
    :filename(str): 下载的实际文件(不需要目录,目录由catalog指定),包含扩展名
    """
    # 下载文件存放目录
    directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "download")
    # 下载分类(directory的子目录)
    catalog = request.args.get("catalog")
    # 下载文件名
    filename = request.args.get("filename")
    app.logger.debug("Want to download a file with catalog: {0}, filename: {1}".format(catalog, filename))
    if catalog and filename:
        if filename.split(".")[-1] in ("txt", "sh", "py", "php"):
            headers = ("Content-Type", "text/plain;charset=utf-8;")
            as_attachment = False
        else:
            headers = ("Content-Disposition", "attachment;filename={}".format(filename))
            as_attachment = True
        if os.path.isfile(os.path.join(directory, catalog, filename)):
            response = make_response(send_from_directory(directory=os.path.join(directory, catalog), filename=filename, as_attachment=as_attachment))
            response.headers[headers[0]] = headers[1]
        else:
            response = make_response("Not Found File")
    else:
        response = make_response("Invalid Download Request")
    return response