ajax - Extjs 4 通过ajax调用下载文件

标签 ajax extjs download tornado

问题很简单:当我提交表单时,我必须下载一个文件,提交表单时这是一个 ajax 调用,它让我使用从表单、服务器端获取的数据构建一个文件,然后将其作为链接到警报。事实是,我的老板希望直接下载文件,而不是通过警报中的链接下载。所以我必须通过 tornado(web) 确保该文件在服务器端可用:

        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=clients_counter.zip')
        with open("static/clients_counter.zip", 'r') as f:
            while True:
                data = f.read()
                if not data:
                    break
        self.write(data)
        self.finish()

服务器端代码似乎工作正常,但客户端(extjs4.1)确实是一场噩梦。这就是我的 ajax 调用现在的样子,但它不起作用:
Ext.Ajax.request({
method : "GET",
url : 'http://whatever.com/count?client='+client+'&start='+start+'&end='+end,
timeout : 30000,
success :
         function (response) {
    //Ext.Msg.alert(response.responseText);
            desktop.getWindow('count-win').doClose();
            return response;
       }//handler,
     failure : 
     function(response) {
    alert("Wrong request");
    }});

最佳答案

在阅读了来自 Ext JS 论坛和这里的 stackoverflow 的各种来源之后,下面是我选择的方法(使用 Ext JS 4.2.1 版):

downloadFile: function(config){
    config = config || {};
    var url = config.url,
        method = config.method || 'POST',// Either GET or POST. Default is POST.
        params = config.params || {};

    // Create form panel. It contains a basic form that we need for the file download.
    var form = Ext.create('Ext.form.Panel', {
        standardSubmit: true,
        url: url,
        method: method
    });

    // Call the submit to begin the file download.
    form.submit({
        target: '_blank', // Avoids leaving the page. 
        params: params
    });

    // Clean-up the form after 100 milliseconds.
    // Once the submit is called, the browser does not care anymore with the form object.
    Ext.defer(function(){
        form.close();
    }, 100);

}

关于ajax - Extjs 4 通过ajax调用下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499959/

相关文章:

javascript - 跨平台(iPhone、Android等)手机文件下载

javascript - 如何动态绑定(bind)ajax数据中的jquery静态数据

javascript - 双异步AJAX函数

php - ckeditor textarea 的内容不通过 Ajax Jquery 发送

javascript - ExtJS 在打开其他窗口之前关闭窗口

javascript - Ext.apply 不适用于 ExtJS 中的监听器

asp.net - C# Asp Net 在 Chrome 12 中下载时出现问题

php - 使用PHP导出XML,通过AJAX将其拉入DOM,但xml不可见

javascript - 如何对 ArrayStore 进行排序?

excel - 使用curl下载excel文件