支持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();
}		

  

原文地址:https://www.cnblogs.com/coolyylu/p/10081588.html