• 支持chrome30下载文件


    function downloadX(url ,fileName){							
    		const xhr = new XMLHttpRequest();
    
    		xhr.open('GET', url, true);
    		xhr.responseType = 'blob';
    		xhr.onload = function() {
    			if (xhr.status === 200) {
    				downloadFile(fileName,xhr.response);				
    			}
    		};
    
    		xhr.send();
    }	
    	
    
    function IE_downloadFile(fileName, content) {
    
        var ifr = document.createElement('iframe');
    
        ifr.style.display = 'none';
    
    
        document.body.appendChild(ifr);
        ifr.contentWindow.document.write(content)
    
        //navigator.userAgent.indexOf("MSIE 6.0") > 0 || navigator.userAgent.indexOf("MSIE 7.0") > 0 || 
        if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
            fileName = fileName + ".txt";
        }
        ifr.contentWindow.document.execCommand('SaveAs', false, fileName);
    
        document.body.removeChild(ifr);
    
    }
    
    function X_downloadFile(fileName, content) {
        var aLink = document.createElement('a');
        var blob = new Blob([content]);
        var evt = new MouseEvent("click", { "view": window, "bubbles": false, "cancelable": false });                
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(evt);    
    }
    
    function downloadFile(fileName, content) {
        if (!/Trident|MSIE/.test(navigator.userAgent))
            return X_downloadFile(fileName, content);
        else
            return IE_downloadFile(fileName, content);
    
    }
    

      

    只是为了chrome30的简单版本

    function downloadX(url, fileName) {
        const xhr = new XMLHttpRequest();
    
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            if (xhr.status === 200) {
    
                var aLink = document.createElement('a');
                var blob = new Blob([xhr.response]);
                var evt = new MouseEvent("click", { "view": window, "bubbles": false, "cancelable": false });
                aLink.download = fileName;
                aLink.href = URL.createObjectURL(blob);
                aLink.dispatchEvent(evt);
            }
        };
    
        xhr.send();
    }		
    

      

  • 相关阅读:
    .NET Core log4net 使用(转贴)
    Tomcat的工作原理
    Servlet工作原理
    java实现快速排序
    正则表达式积累
    js常用知识真理
    最常用的的设计模式
    【设计模式】单例设计模式
    java中堆栈区别,递归和迭代区别
    Struts2的工作原理
  • 原文地址:https://www.cnblogs.com/coolyylu/p/10081588.html
Copyright © 2020-2023  润新知