方法一:
download
属性:(可以触发下载,也能指定下载文件名)
<a href="Uploads/test.png" download="123.png">下载</a>
如果下载文件的后缀与源文件保持一致,可以设置缺省文件名:
<a href="Uploads/test.png" download="123">下载</a>
方法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>调用浏览器下载功能(兼容各主流浏览器)</title>
</head>
<style>
img#downImg{
display: none;
}
</style>
<body>
<div id="down">
<a id="downLoad">下载</a>
</div>
</body>
</html>
<script type="text/javascript">
//①判断浏览器类型
function myBrowser() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1;
if(isOpera) {
return "Opera"
}; //判断是否Opera浏览器
if(userAgent.indexOf("Firefox") > -1) {
return "FF";
} //判断是否Firefox浏览器
if(userAgent.indexOf("Chrome") > -1) {
return "Chrome";
}
if(userAgent.indexOf("Safari") > -1) {
return "Safari";
} //判断是否Safari浏览器
if(userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
return "IE";
}; //判断是否IE浏览器
if(userAgent.indexOf("Trident") > -1) {
return "Edge";
} //判断是否Edge浏览器
}
//②IE浏览器图片保存(IE其实用的就是window.open)
function SaveAs5(imgURL) {
var oPop = window.open(imgURL, "", "width=1, height=1, top=5000, left=5000");
for(; oPop.document.readyState != "complete";) {
if(oPop.document.readyState == "complete") break;
}
oPop.document.execCommand("SaveAs");
oPop.close();
}
//③下载函数(区分IE和非IE部分)
function oDownLoad(url) {
if(myBrowser() === "IE" || myBrowser() === "Edge") { //IE (浏览器)
SaveAs5(url);
console.log(1)
} else if (myBrowser()==="Safari"){ //不支持iOS Safari
odownLoad.href="#";
} else { //!IE (非IE)
odownLoad.href = url;
odownLoad.download = "";
}
}
//④点击事件下载(只需更改图片路径即可)
var odownLoad = document.getElementById("downLoad");
odownLoad.onclick = function() {
oDownLoad("Uploads/1.jpg")
}
</script>