繁体   English   中英

下载的txt文件被视为html,但不包括空行

[英]txt file downloaded is being viewed as html and that is excluding the empty lines

我有一个在本地正常运行的Python / Flask应用程序。 我已经将它部署到了云(pythonanywhere)上,并且所有工作都在那里进行,除了一个文件正在下载为html格式的用户外,因此该文件的空行被排除在外。 该文件是txt。 当用户单击它时,它将在记事本上打开。 如果在notepad ++中打开该文件,则空行应以应有的方式显示。

按照Flask代码发送该文件:

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

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

我尝试在“ Content-Disposition”之前添加“ Content type text / plain”,但我相信它是默认设置,因此没有效果。

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

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

如果您尝试做出响应(例如,如果您正在内存中生成数据,则make_response默认为text/html (这只是快捷方式,不适用于您的情况)。甚至可以直接在其中创建响应为了使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM