JS实现文件下载(适应多种浏览器)

来源:互联网 发布:12315投诉有用吗淘宝 编辑:程序博客网 时间:2024/05/20 02:29
<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>JS实现文件上传下载</title></head><body><a href="javascript:void(0);" id="oDownLoad" onclick="oDownLoad('1.pdf','oDownLoad')">下载</a></body><script>    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浏览器    }    function oDownLoad(url,id) {        if (myBrowser()==="IE" || myBrowser()==="Edge"){            var oPop = window.open(url,"","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();        }else{            //!IE            var odownLoad=document.getElementById(id);            odownLoad.href=url;            odownLoad.download="";        }    }</script></html>


注:在html同一目录下准备一个1.pdf文件。

原创粉丝点击