2015-04-01 35 views
0

我有一個Python/Flask應用程序在本地工作正常。我已經將它部署到了雲(pythonanywhere),除了正在下載到用戶的文件(即將以html格式)之外,它們都在那裏工作,因此文件的空行被排除。該文件是txt。當用戶點擊它時,它會在記事本上打開。如果在記事本++中打開該文件,則空行應該以它的方式存在。下載的txt文件被視爲html,這是排除空行

繼瓶代碼來發送文件:

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

如果我使用「內聯,而不是掛職」,空行是在瀏覽器上直接OK顯示。

我試圖在「Content-Disposition」之前添加「Content type text/plain」,但我相信它是默認的,所以沒有效果。

任何人都知道用戶如何看到作爲txt文件,而不是直接使用記事本打開時的html?

回答

3

如果您只是想發送服務器上的現有文件,請使用send_from_directory

如果你想做出響應(例如,如果你生成內存中的數據,make_response默認爲text/html(它只是一個快捷方式是不是適合你的情況)。創建響應甚至直接在

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) 
爲了覆蓋該使用 app.response_class

這是一個小例子證明這兩種技術。