ajax下載文件實現接受json數據和文件流兩種形式


需求:前端下載文件,調用后端下載接口,如果后端報錯需要給出錯誤信息如果沒有報錯可以正常下載。

解決方案:

方案一:首先想到的是分成兩個接口首先詢問是否可以下載,如果可以下載再去下載

方案二:通過原生ajax請求的狀態碼區分

function xhrGet (type ,url, fn){
	    // XMLHttpRequest對象用於在后台與服務器交換數據   
	    var xhr = new XMLHttpRequest();            
	    xhr.open(type, url, true);
	    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
	    xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
	    xhr.onreadystatechange = function() {
	      	// readyState == 4說明請求已完成
	      	if(xhr.readyState == this.HEADERS_RECEIVED){
	      		if(xhr.getResponseHeader('Content-Type')=='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
	      			xhr.abort();
	      			window.location.href=url;
	      			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();
	}

  我們onreadystatechange方法的回調函數是readyState,readyState標識不同的狀態,當readyState==this.HEADERS_RECEIVED時,即服務器的相應頭部已返回,那么我們獲取頭部的content-type,如果是application/json就是錯誤信息,執行正常的操。如果是下載文件對應的content-type,比如excel文件為'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',我們放棄該次,直接去訪問該文件的下載地址即可正常下載。

附上readystate各階段狀態信息。

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM