zoukankan      html  css  js  c++  java
  • Js下载文件到本地(兼容多浏览器)

    在客户端通过js下载文件,试过几种下载方式,iframe方式仅限于IE浏览器,window.open(url),location.href=url 这两种方式在chrome浏览器还会是直接打开文件而不是下载,百度N久没有结果,在谷歌还是找到答案了,下载链接在此。

    window.downloadFile = function (sUrl) {
    
        //iOS devices do not support downloading. We have to inform user about this.
        if (/(iP)/g.test(navigator.userAgent)) {
            alert('Your device does not support files downloading. Please try again in desktop browser.');
            return false;
        }
    
        //If in Chrome or Safari - download via virtual link click
        if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
            //Creating new link node.
            var link = document.createElement('a');
            link.href = sUrl;
    
            if (link.download !== undefined) {
                //Set HTML5 download attribute. This will prevent file from opening if supported.
                var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
                link.download = fileName;
            }
    
            //Dispatching click event.
            if (document.createEvent) {
                var e = document.createEvent('MouseEvents');
                e.initEvent('click', true, true);
                link.dispatchEvent(e);
                return true;
            }
        }
    
        // Force file download (whether supported by server).
        if (sUrl.indexOf('?') === -1) {
            sUrl += '?download';
        }
    
        window.open(sUrl, '_self');
        return true;
    }
    
    window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
  • 相关阅读:
    Dubbo 节点telnet测试
    node.js 文件下载
    node.js获取ip及mac
    excel中根据A列筛选B列填充C列
    django在读取数据库时未筛选到符合条件的记录会报错
    django分页功能
    django中命令行调试程序
    Python中if-else的多种写法
    python自定义函数的参数之四种表现形式
    python类变量和实例变量的区别
  • 原文地址:https://www.cnblogs.com/habin/p/6703257.html
Copyright © 2011-2022 走看看