我有一个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?
发布于 2015-04-02 03:31:18
如果您只是尝试发送服务器上的现有文件,请使用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)https://stackoverflow.com/questions/29398651
复制相似问题