javascript - 强制浏览器下载 Html 页面而不是渲染它

标签 javascript jquery html ajax download

我有一个在新窗口中弹出页面的脚本,数据是通过 AJAX 调用接收的。

代码是:

$scope.downloadExcell = function () {
            $http.post('/Monitor/DownloadExcell', { model: $scope.formModel })
            .success(function (data) {           

                 var html = "<!DOCTYPE html><html><head><meta http-equiv="
                +"'Content-type' content='application/vnd.ms-excel' />"
                +"<meta http-equiv='content-disposition' content='attachment; filename=fegc.xls' />"
                +"<title>_excell</title></head><body>";

                html = html + "<table style='width:100%;' >";

                html = html + "<tr>";
                for (prop in data[0]) {
                    html = html + "<td>" + prop + "</td>";
                }
                html = html + "</tr>";

                for (key in data) {
                    html = html + "<tr>";
                    for (prop in data[key]) {
                        html = html + "<td>" + data[key][prop] + "</td>";
                    }
                    html = html + "</tr>";
                }

                html = html + "</table>" + "</body>" + "</html>";

                var w = window.open();
                $(w.document.body).html(html);

            });

现在,我希望浏览器将页面下载为 .xlsx 文件 当它被加载而不是渲染它时。

这可能吗?想不通这个。

我尝试使用元数据,但它们只是被忽略了。

谢谢!

信息:这是一个 ASP.NET MVC 网络应用程序

最佳答案

您可以执行以下技巧。您创建一个 <a>标记,然后您给他一个自定义对象 URL 作为其 href属性。

这将导致 <a>强制下载 mimetype 集。

您可以将您的 HTML 放在 content 中多变的。

var name ='excel-file.xlsx';  // The name of the file to be downloaded
var content = 'data';         // The contents of the file
var mimetype = 'application/vnd.ms-excel'; // The mimetype of the file for the browser to handle

// Add the <a> in the end of the body. Hide it so that it won't mess with your design. 
$('body').append('<a class="download-trigger" style="display:none;"></a>');

var a = $('.download-trigger')[0];
a.href = window.URL.createObjectURL(new Blob([content], {
    type: mimetype
}));
a.download = name;
a.textContent = 'Download';
a.click();

注意:您只需要附加 <a><body>只有一次,而不是每次执行此代码时。

这是一个演示 http://jsfiddle.net/5dyunv6w/ (打开页面即开始下载)

关于javascript - 强制浏览器下载 Html 页面而不是渲染它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742894/

相关文章:

javascript - 旋转点的位置

Javascript Int 参数变形 >= 000100

javascript - 关于正则表达式模式的解释

javascript - Node.appendChild 的参数 1 不是对象

php - 如何在不使用多个查询字符串刷新的情况下加载内容

javascript - Jquery 切换和传递数据

html - 如何设置输入的背景透明度?

javascript - element.scrollIntoView 切断顶部

html - 在大约 :blank 更改背景颜色

javascript - 使用 Javascript(可能使用 Canvas )获取背景图像的 urldata