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

    实现点击 用纯 js(非jquery)  下载文件到本地 

    自己尝试,加网上找了好久未果,如:

    window.open(url)   location.href=url   form表单提交   iframe  体验和浏览器兼容都不完美

    还是博客园一兄弟给了方法,非常感谢!

    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;
  • 相关阅读:
    SpringMVC传值、转发、重定向例子
    内存、指针操作函数
    文件、磁盘操作函数
    字符串、数组操作函数 Copy Concat Delete Insert High MidStr Pos SetLength StrPCopy TrimLeft
    Delphi代码模拟“显示桌面”的功能
    SQLite 入门教程(四)增删改查,有讲究
    NET Core
    Publisher/Subscriber 订阅-发布模式
    数据分片
    C#调用Java方法
  • 原文地址:https://www.cnblogs.com/xiangsj/p/8616885.html
Copyright © 2011-2022 走看看