zoukankan      html  css  js  c++  java
  • 支持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();
    }		
    

      

  • 相关阅读:
    CSS布局之盒子模型[二]
    CSS布局之盒子模型[一]
    CSS文本相关之垂直排列[5]
    网站迁移之后,中文路径都变成乱码
    Linux中shell搜索多文件中的字符串
    mysql数据库报错
    使用Flarum轻松搭建自己的论坛
    CSS雪碧图-html优化
    CSS-定位模式
    ul当做div标签的使用
  • 原文地址:https://www.cnblogs.com/coolyylu/p/10081588.html
Copyright © 2011-2022 走看看