2012-09-06 34 views
0

我想在響應中將文件作爲附件進行流式傳輸。我有這樣的功能:response.stream和web2py_component:無法將文件作爲附件流式傳輸

def form_query(): 
    response.flash = str(request.args(0)) 
    response.generic_patterns = ['load'] 
    response.headers['Content-Type'] = gluon.contenttype.contenttype('.txt') 
    response.headers['Content-Disposition'] = 'attachment; filename=somefile.txt' 
    #more code goes in here to process request.args here. 
    #Ultimately, the controller is expected to return a dict containing a table and the file to be streamed as an attachment. For now just trying to get the file streamed. 
    return response.stream(open('somefile.txt'),chunk_size=1024) 

當我通常把這種控制器(如果我把流碼內指數()和去的index.html爲EG)它通過打開一個下載彈出保存文件的響應到磁盤。但是,當我有這種被稱爲從index.html中web2py_component目標函數(以填補響應一個div)是這樣的:

web2py_component("{{=URL('reports', 'form_query.load')}}" + "/" + jQuery(this).val(), target='div_form_query'); 

它呈現DIV「div_form_query」裏面的文件,而不是彈出一個下載窗口。

任何想法如何使用web2py_component作爲附件呈現文件。我正在使用web2py_component,因爲我想根據選擇列表將條件加載到該div目標(div_form_query)中,該列表以選項表作爲選項。中的index.html看起來像:

{{extend 'layout.html'}} 

{{=SELECT('Select a report', 
*[OPTION(repts[i].descr, _value=str(repts[i].report)) for i in range(len(repts))], _id="rep_type")}} 

<div id="div_form_query"></div> 

<script> 
    jQuery(document).ready(function(){ 
    jQuery('#rep_type').change(function(){ 
    web2py_component("{{=URL('reports', 'form_query.load')}}" + "/" + jQuery(this).val(), target='div_form_query'); 
    }); 

    }); 
</script> 
{{end}} 

感謝, MAVE

+0

如果您希望將文件作爲附件下載,那麼組件div有什麼意義?該div意味着你想在頁面上顯示一些東西。 – Anthony

+1

安東尼,是的,除了控制器觸發下載之外,DIV必須顯示控制器的響應。抱歉,如果上面不清楚,我希望控制器(form_query)做兩件事:返回一個包含表進入目標DIV並觸發文件下載。上面的form_query()代碼不會顯示返回包含表格的dict的代碼。 – maverick

+0

您需要進行兩個不同的調用 - 一個用於表格,另一個用於文件(對於那些成爲兩個單獨的函數可能有意義)。查看更新的答案。 – Anthony

回答

1

也許這會做你想要什麼:

jQuery('#rep_type').change(function(){ 
    var choice = jQuery(this).val(); 
    web2py_component('{{=URL('reports', 'create_table')}}' + '/' + choice, 
    target='div_form_query'); 
    window.open('{{=URL('reports', 'form_query')}}' + '/' + choice); 
}); 

另一種選擇是隻叫web2py_component()以上,然後在組件HTML中,包含執行以下操作的腳本:

window.open('{{=URL('reports', 'form_query')}}' + '/' + choice);