首页 > 解决方案 > 在firefox上使用ajax从服务器下载文件

问题描述

如何从 URL 下载文件。

以下代码仅适用于 chrome:

$.ajax({
                    url: '/xls',
                    data: {_csrf: this.csrf, hist:historicData },
                    method: 'POST',
                    // beforeSend: function(xhr){
                    //     xhr.setRequestHeader('historic', historicData);
                    // },
                    xhrFields: {
                        responseType: 'blob'
                    },                    
                    success: function (data) {
                        var a = document.createElement('a');
                        a.style = "display: none";  
                        var blob = new Blob(data, {type: "application/octet-stream"});
                        var url = window.URL.createObjectURL(blob);
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        setTimeout(function(){
                            document.body.removeChild(a);
                            window.URL.revokeObjectURL(url);  
                        }, 100);  

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                       alert(xhr.status);
                       alert(thrownError);
                   }
                });

在 Firefox 上没有发生任何事情。

火狐版本:63.0.3(64位)

Chrome 版本:70.0.3538.110

网络 :

请求地址:http://localhost:3000/xls请求方法:POST 远程地址:[::1]:3000 状态码:200 ok

预览:AAB4bC93b3JrYm9vay54bWxQSwECFAAKAAAAAAD.......

响应标头 (519 B) Cache-Control no-cache, private, no-store, m…=0, post-check=0, pre-check=0 Connection keep-alive Content-disposition attachment;filename=xingamento Content-Type
application/vnd.ms-excel 日期 Thu, 29 Nov 2018 23:38:17 GMT Strict-Transport-Security max-age=15552000; includeSubDomains Transfer-Encoding chunked X-Content-Type-Options nosniff X-DNS-Prefetch-Control off X-Download-Options noopen X-Frame-Options SAMEORIGIN X-XSS-Protection 1;模式=块

标签: javascriptgoogle-chromefirefox

解决方案


推荐阅读