简体   繁体   English

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

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

I've a Python/Flask app that is working ok locally. 我有一个在本地正常运行的Python / Flask应用程序。 I have deployed it to the cloud (pythonanywhere) and it is all working on there as well except for a file that is being downloaded to the user that is coming as html, so the empty lines of the file are being excluded. 我已经将它部署到了云(pythonanywhere)上,并且所有工作都在那里进行,除了一个文件正在下载为html格式的用户外,因此该文件的空行被排除在外。 That file is txt. 该文件是txt。 When the user click on that, it opens on notepad. 当用户单击它时,它将在记事本上打开。 If opening that file in notepad++ the empty lines are there in the way it should be. 如果在notepad ++中打开该文件,则空行应以应有的方式显示。

Following the Flask code to send that file: 按照Flask代码发送该文件:

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

If I use "inline instead of attachment", the empty lines are showed OK directly on the browser. 如果我使用“内联而不是附件”,则空行将直接在浏览器上显示为OK。

I've tried to add "Content type text/plain" before "Content-Disposition", but I believe that it is the default, so, no effect. 我尝试在“ Content-Disposition”之前添加“ Content type text / plain”,但我相信它是默认设置,因此没有效果。

Anyone knows how could the user see that as txt file, instead of html when opening directly using notepad for example? 任何人都知道,例如在直接使用记事本打开时,用户如何将其视为txt文件而不是html?

If you're just trying to send an existing file on the server, use send_from_directory . 如果您只是想发送服务器上的现有文件,请使用send_from_directory

If you're trying to make a response (for example, if you're generating data in memory, make_response defaults to text/html (it's just a shortcut which isn't applicable in your case). Create a response even more directly in order to override that using app.response_class . 如果您尝试做出响应(例如,如果您正在内存中生成数据,则make_response默认为text/html (这只是快捷方式,不适用于您的情况)。甚至可以直接在其中创建响应为了使用app.response_class覆盖它。

This is a small example demonstrating both techniques. 这是展示这两种技术的一个小例子。

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