Extjs 4 downloading a file through ajax call

前端 未结 7 1327
陌清茗
陌清茗 2021-01-06 16:16

The problem is very simple: i have to download a file when i submit a form, it\'s an ajax call when the form is submitted which lets me build a file with the data taken from

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 17:06

    The following code used to download the file using extjs 5 or 6. Add the following code to method and invoke this for button action. This downloads the file directly insteadof opening in new tab.

    use an iframe like this:

    /**
     * prints the file
     */
    printReport: function () {
        var url = 'downloadURL';
        Ext.Ajax.request({
            url: url,
            method: 'GET',
            autoAbort: false,
            success: function(result) {
                if(result.status == 204) {
                    Ext.Msg.alert('Empty Report', 'There is no data');
                } else if(result.status == 200) {
                    Ext.DomHelper.append(Ext.getBody(), {
                        tag:          'iframe',
                        frameBorder:  0,
                        width:        0,
                        height:       0,
                        css:          'display:none;visibility:hidden;height:0px;',
                        src:          url
                    });
                }
            },
            failure: function() {
                //failure here will automatically
                //log the user out as it should
            }
        });
    }
    

    Copied the answer from extjs forum

    Option:2 If you want to open the file in new tab

        /**
     * open file in tab
     */
    openReport: function () {
        var url = 'downloadURL';
        Ext.Ajax.request({
            url: url,
            method: 'GET',
            autoAbort: false,
            success: function(result) {
                if(result.status == 204) {
                    Ext.Msg.alert('Empty Report', 'There is no data');
                } else if(result.status == 200) {
                    var win = window.open('', '_blank');
                    win.location = url;
                    win.focus();
                }
            },
            failure: function() {
                //failure here will automatically
                //log the user out as it should
            }
        });
    }
    

提交回复
热议问题