ajax download a file, there is an exception error, no abnormal achieve direct download

Requirements: front-end download a file, call the back-end interface to download, if the back-end error need to give an error message if there is no error can be downloaded properly.

solution:

Option One: the first thought is divided into two interfaces First, ask if you can download, if you can go download download

Option II: native ajax request via a state code to distinguish

xhrGet function (type, URL, Fn) { 
	    // the XMLHttpRequest object is used to exchange data with the server in the background    
	    var = new new XHR the XMLHttpRequest ();             
	    xhr.open (type, URL, to true); 
	    xhr.setRequestHeader ( 'X--Requested- with ',' the XMLHttpRequest '); 
	    xhr.setRequestHeader (' the Accept ',' file application / JSON, text / Plain, * / * '); 
	    xhr.onreadystatechange = function () { 
	      	// the readyState == request. 4 has been completed 
	      	if (xhr.readyState == this.HEADERS_RECEIVED) { 
	      		IF (xhr.getResponseHeader ( 'the Type-the Content') == 'file application / vnd.openxmlformats-officedocument.spreadsheetml.sheet') { 
	      			xhr.abort (); 
	      			the window.location. URL = the href; 
	      			return; 
	      		} 
	      	}
	      	if (xhr.readyState == 4 && xhr.status == 200) { 
	        	// 从服务器获得数据 
	        	try{
	        		let res = JSON.parse(xhr.responseText);
	        		if(res.rc=='9'){
						window.location.href=location.protocol+"//"+location.host+'/api/account/home?url='+encodeURIComponent(location.protocol+"//"+location.host+'/#/home');
						return;
					}
					if(res.rc=='3'){
						window.location.href="#/403";
						return;
					}
	        		fn.call(this, res);
	        	}catch (error){
	        		  
	        	}
	        	
	      	}
	    };
	    xhr.send();
	}

  Our method of callback function onreadystatechange readyState is, identify different readyState status, when readyState == this.HEADERS_RECEIVED, namely the head of the corresponding server has returned, then we get the head of the content-type, if it is application / json is wrong information, the normal operation. If you downloaded the file corresponding to the content-type, such as excel file as 'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet', we give up the time, direct access to the Download the file to download normal.

Readystate attach various stages of status information.

 

Guess you like

Origin www.cnblogs.com/leejay6567/p/11363055.html