最先网上答案讨论比较多的是这一种:
**通过iframe下载
/**
* content 下载的url
*/
function download2(content) {
try{
$(".iframe_down").remove().end();
var urlFile=content;
var elemIF = document.createElement("iframe");
elemIF.src = urlFile;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}
catch(e){
}
}
缺点:下载不稳定,偶尔会下载两次,尚未查出原因
/*优化*/
通过尝试,找到了完美的方法:通过表单下载
//页面html元素
<iframe style="display: none" name="if_down"></iframe>
<form method="post" action="" id="if_down" target="if_down"></form>
/**
* content 下载的url
* id url中需要传的参数
*/
function download2(content, id) {
try{
var $eleForm = $("#if_down");
$eleForm.attr("action", content);
//url中需要带的参数
var input = $("<input>");
input.attr("type", "hidden");
input.attr("name", "id");
input.attr("value", id);//参数id
$eleForm.append(input);
$eleForm.submit();
}
catch(e){
}
}
完美解决第一个中所带来的问题,目前没有发现不兼容的浏览器,缺点是在这种post表单提交方式中,无法直接在url中带参,但是可以通过上述代码中的input方式将参数带入。
网页文件下载优化方案
本文探讨了网页上文件下载的两种方法:使用iframe和表单提交。iframe方法存在下载不稳定的问题,而表单提交方法则提供了更稳定的下载体验,且兼容性良好。文章详细介绍了如何通过JavaScript动态创建表单并提交请求来实现文件下载。
226

被折叠的 条评论
为什么被折叠?



