我想将文件作为响应中的附件进行流式传输。我有这个功能:
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()中并转到index.html),它会打开下载弹出窗口将文件保存到磁盘。但是,当我从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
也许这会达到你想要的效果:
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);