【问题标题】:ExtJS 4 - How to download a file using Ajax?ExtJS 4 - 如何使用 Ajax 下载文件?
【发布时间】:2011-10-12 12:35:42
【问题描述】:

我有一个包含各种文本字段和两个按钮的表单 - 导出到 Excel 和导出到 CSV。

用户可以为表单中的不同字段提供值并单击其中一个按钮。

预期的行为是应该触发 Ajax 请求,携带字段的值作为参数,并且应该下载所选文件(Excel/CSV,按按钮单击)(我没有提交表单,因为需要完成在提交之前对值进行一些处理)。

我一直在Ajax请求下载成功函数中使用如下代码:

result  =   Ext.decode(response.responseText);

try {
    Ext.destroy(Ext.get('testIframe'));
}

catch(e) {}

Ext.core.DomHelper.append(document.body, {
    tag: 'iframe',
    id:'testIframe',
    css: 'display:none;visibility:hidden;height:0px;',
    src: result.filename,
    frameBorder: 0,
    width: 0,
    height: 0
});

在服务器上物理创建文件的情况下,上述代码运行良好。但是在我当前的项目中,文件不是在服务器上创建的,而是内容只是以适当的标题流式传输到浏览器。

因此,当文件在服务器上不存在时,有没有办法使用 Ajax 下载文件?只是要补充一点,我有一长串参数需要发送到服务器,因此无法将它们全部添加到 iframe 的 src 中。

有人可以指导吗?

提前感谢您的帮助。

【问题讨论】:

  • 感谢分享链接 Amol。我经历了它,我没有使用它的唯一原因是我无法以这种方式将参数传递给服务器。如问题中所述,我有一长串参数,无法附加到 URL 并传递给服务器。您可以建议解决此问题吗?再次感谢。
  • 关于通过 POST 下载文件,请参阅 stackoverflow.com/questions/7563791/… 虽然我目前不喜欢那里的最佳答案,因为它似乎忽略了使用 javascript 启动下载的要求。

标签: javascript ajax extjs download extjs4


【解决方案1】:

你可以像这样使用组件:

Ext.define('CMS.view.FileDownload', {
    extend: 'Ext.Component',
    alias: 'widget.FileDownloader',
    autoEl: {
        tag: 'iframe', 
        cls: 'x-hidden', 
        src: Ext.SSL_SECURE_URL
    },
    stateful: false,
    load: function(config){
        var e = this.getEl();
        e.dom.src = config.url + 
            (config.params ? '?' + Ext.urlEncode(config.params) : '');
        e.dom.onload = function() {
            if(e.dom.contentDocument.body.childNodes[0].wholeText == '404') {
                Ext.Msg.show({
                    title: 'Attachment missing',
                    msg: 'The document you are after can not be found on the server.',
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR   
                })
            }
        }
    }
});

把它放在视口中的某个地方,例如:

{
    region: 'south',
    html: 'South',
    items: [
        {
            xtype: 'FileDownloader',
            id: 'FileDownloader'
        }
    ]
}

不要忘记在您的视口类中要求它:

requires: [
    'CMS.view.FileDownload'
]

动作处理程序可能如下所示:

var downloader = Ext.getCmp('FileDownloader')
downloader.load({
    url: '/attachments/' + record.get('id') + '/' + record.get('file')
});

在响应中有 Content-Disposition 标头非常重要,否则不会下载任何内容。

问候http://www.quispiam.com/blog/post.php?s=2011-06-09-download-a-file-via-an-event-for-extjs4 这东西对我有用。

【讨论】:

  • 这很好用,除了 onload 在 4.2.2 中永远不会触发 dom.onload 事件
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
相关资源
最近更新 更多