XHR post请求下载文件

            var filename = 'test.xlsx';
            var xhr = new XMLHttpRequest();
            xhr.open('POST', downloadExcel, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.responseType = 'blob';
            xhr.onload = function(res) {
                if (this.status === 200) {
                    var type = xhr.getResponseHeader('Content-Type');
                    var blob = new Blob([this.response], {type: type});
                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        /*
                         * For IE
                         * >=IE10
                         */
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        /*
                         * For Non-IE (chrome, firefox)
                         */
                        var URL = window.URL || window.webkitURL;
                        var objectUrl = URL.createObjectURL(blob);
                        if (filename) {
                            var a = document.createElement('a');
                            if (typeof a.download === 'undefined') {
                                window.location = objectUrl;
                            } else {
                                a.href = objectUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                                a.remove();
                            }
                        } else {
                            window.location = objectUrl;
                        }
                    }
                }
            }
            xhr.send(JSON.stringify(list));

  

原文地址:https://www.cnblogs.com/jiehanshi/p/12627112.html