【问题标题】:txt file downloaded is being viewed as html and that is excluding the empty lines下载的 txt 文件被视为 html 并且不包括空行
【发布时间】:2015-04-01 18:57:33
【问题描述】:

我有一个在本地运行良好的 Python/Flask 应用程序。我已将它部署到云(pythonanywhere),除了一个以 html 形式下载给用户的文件外,它也都在那里工作,因此文件的空行被排除在外。那个文件是txt。当用户单击它时,它会在记事本上打开。如果在记事本 ++ 中打开该文件,则空行会以应有的方式出现。

按照 Flask 代码发送该文件:

response = make_response(result)
response.headers["Content-Disposition"] = "attachment; filename=file_to_user.txt"

如果我使用“内联而不是附件”,空行会直接在浏览器上显示。

我尝试在“Content-Disposition”之前添加“Content type text/plain”,但我认为这是默认设置,所以没有效果。

任何人都知道,例如,当直接使用记事本打开时,用户如何将其视为 txt 文件而不是 html?

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    如果您只是想发送服务器上的现有文件,请使用send_from_directory

    如果您尝试做出响应(例如,如果您在内存中生成数据,make_response 默认为 text/html(这只是一个快捷方式,不适用于您的情况)。创建一个甚至 more 直接响应,以便使用 app.response_class 覆盖它。

    这是一个展示这两种技术的小例子。

    from flask import Flask, send_from_directory
    
    app = Flask(__name__)
    
    @app.route('/file')
    def download_file():
        # change app.root_path to whatever the directory actually is
        # this just serves this python file (named example.py) as plain text
        return send_from_directory(
            app.root_path, 'example.py',
            as_attachment=True, mimetype='text/plain'
        )
    
    @app.route('/mem')
    def download_mem():
        # instantiate the response class directly
        # pass the mimetype
        r = app.response_class('test data\n\ntest data', mimetype='text/plain')
        # add the attachment header
        r.headers.set('Content-Disposition', 'attachment', filename='test_data.txt')
        return r
    
    app.run('localhost', debug=True)
    

    【讨论】:

      猜你喜欢
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多