我有一个在新窗口中弹出页面的脚本,数据是通过 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/