[英]Force the browser to download an Html Page instead of rendering it
我有一个在新窗口中弹出页面的脚本,数据是通过 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 WEB 应用程序
您只能在使用服务器端语言的情况下执行此操作,
// PHP
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-disposition: attachment; filename=filtro.xls");
您可以执行以下技巧。 您创建了一个<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/ (打开页面时会开始下载)
使用此功能下载文件。
function SaveToDisk(fileURL, fileName) {
//alert("yes i m working");
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.