首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >下载的txt文件以html格式查看,但不包括空行

下载的txt文件以html格式查看,但不包括空行
EN

Stack Overflow用户
提问于 2015-04-02 02:57:34
回答 1查看 390关注 0票数 0

我有一个Python/Flask应用程序,在本地工作正常。我已经将它部署到云端(pythonanywhere),除了一个以html格式下载给用户的文件之外,所有的工作都在那里进行,所以文件中的空行被排除在外。那个文件是txt。当用户点击它时,它会在记事本上打开。如果在notepad++中打开该文件,那么空行的位置应该是正确的。

按照Flask代码发送该文件:

代码语言:javascript
复制
response = make_response(result)
response.headers["Content-Disposition"] = "attachment; filename=file_to_user.txt"

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

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

有没有人知道,当用户使用记事本直接打开时,如何将其显示为txt文件,而不是html?

EN

回答 1

Stack Overflow用户

发布于 2015-04-02 03:31:18

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

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

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

代码语言:javascript
复制
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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29398651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档