[英]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.