Excel 다운로드(Ajax 방식 / XMLHttpRequest 방식)

Hanbyul·2023년 11월 30일

Ajax 방식

$("#btnDownload").click(function(event) {
    event.preventDefault(); 
    
    -> 버튼의 기본 동작을 중단합니다. 여기서는 폼 제출을 막습니다.
    
    
    if (confirm("다운로드 하시겠습니까?")) { 
    
    -> // 사용자에게 다운로드할 것인지 확인합니다.
        
        
        $.ajax({ 
        
        -> AJAX 요청을 보냅니다.
            
            
            url: '/downloadExcel', 
            
            -> 요청을 보낼 URL입니다.
            
            
            method: 'GET', 
            
            -> HTTP 메서드입니다.
            
            
            xhrFields: { 
            
            -> XMLHttpRequest 객체의 필드를 설정합니다.
                
                
                responseType: 'blob'
            },
            
            -> 응답의 타입을 blob으로 설정합니다.
            
            
            success: function(blob) { 
            
            -> 요청이 성공했을 때 실행할 함수입니다.
                
                
                var link = document.createElement('a'); 
                
                -> a 요소를 생성합니다.
                
                
                link.href = window.URL.createObjectURL(blob); 
                
                -> blob URL을 생성하여 href 속성에 설정합니다.
                
                
                link.download = "boardList_data.xlsx"; 
                
                -> 다운로드할 파일의 이름을 설정합니다.
                
                
                link.click(); 
                
                -> a 요소를 클릭하여 파일을 다운로드합니다.
                
                
                alert('엑셀 다운로드에 성공했습니다'); // 성공 메시지를 출력합니다.
            },
            error: function(xhr, status, error) { // 요청이 실패했을 때 실행할 함수입니다.
                console.error('서버 응답:', xhr); // 서버의 응답을 콘솔에 출력합니다.
                console.error('오류 상태:', status); // 오류 상태를 콘솔에 출력합니다.
                console.error('오류 메시지:', error); // 오류 메시지를 콘솔에 출력합니다.
                alert('엑셀 다운로드에 실패했습니다.'); // 실패 메시지를 출력합니다.
            }
        });
    }
});

XMLHttpRequest 방식

$("#btnDownload").click(function(event) {
    event.preventDefault(); 
    
    -> 버튼의 기본 동작을 중단합니다. 여기서는 폼 제출을 막습니다.
    
    
    if (confirm("다운로드 하시겠습니까?")) { 
    
    -> 사용자에게 다운로드할 것인지 확인합니다.
    
    
        var xhr = new XMLHttpRequest(); 
        
        -> XMLHttpRequest 객체를 생성합니다.
        
        
        xhr.open('GET', '/downloadExcel', true); 
        
        -> 요청을 초기화합니다. 여기서는 GET 요청을 '/downloadExcel' URL로 비동기적으로 보냅니다.
        
        
        xhr.responseType = 'blob'; 
        
        -> 응답의 타입을 blob으로 설정합니다.
        
        
        xhr.onload = function(e) { 
        
        -> 요청이 성공했을 때 실행할 함수입니다.
            
            
            if (this.status == 200) { 
            
            -> HTTP 상태 코드가 200이면 요청이 성공했다는 의미입니다.
                
                
                var blob = new Blob([this.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}); 
                
                -> 응답을 Blob 객체로 변환합니다. 여기서는 엑셀 파일임을 명시하기 위해 MIME 타입을 설정합니다.
                
                
                var link = document.createElement('a'); 
                
                -> a 요소를 생성합니다.
                
                
                link.href = window.URL.createObjectURL(blob); 
                
                -> blob URL을 생성하여 href 속성에 설정합니다.
                
                
                link.download = "boardList_data.xlsx"; 
                
                -> 다운로드할 파일의 이름을 설정합니다.
                
                
                link.click(); 
                
                -> a 요소를 클릭하여 파일을 다운로드합니다.
                
                
                alert('엑셀 다운로드에 성공했습니다'); // 성공 메시지를 출력합니다.
            }
        };
        xhr.onerror = function() { // 요청이 실패했을 때 실행할 함수입니다.
            alert('엑셀 다운로드에 실패했습니다.'); // 실패 메시지를 출력합니다.
        };
        xhr.send(); // 요청을 보냅니다.
    }
});

전체코드

	ajax방식
    
    
	$("#btnDownload").click(function(event) {
    event.preventDefault();
	    if (confirm("다운로드 하시겠습니까?")) {
	        $.ajax({
	            url: '/downloadExcel',
	            method: 'GET',
	            xhrFields: {
	                responseType: 'blob'
	            },
	            success: function(blob) {
	                var link = document.createElement('a');
	                link.href = window.URL.createObjectURL(blob);
	                link.download = "boardList_data.xlsx";
	                link.click();
	                alert('엑셀 다운로드에 성공했습니다');
	            },
	            error: function(xhr, status, error) {
	                console.error('서버 응답:', xhr);
	                console.error('오류 상태:', status);
	                console.error('오류 메시지:', error);
	                alert('엑셀 다운로드에 실패했습니다.');
	            }
	        });
	    }
	});



	XMLHttpRequest 방식
	
	
	$("#btnDownload").click(function(event) {
    event.preventDefault();
	    if (confirm("다운로드 하시겠습니까?")) {
	        var xhr = new XMLHttpRequest();
	        xhr.open('GET', '/downloadExcel', true);
	        xhr.responseType = 'blob';
	        xhr.onload = function(e) {
	            if (this.status == 200) {
	                var blob = new Blob([this.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
	                var link = document.createElement('a');
	                link.href = window.URL.createObjectURL(blob);
	                link.download = "boardList_data.xlsx";
	                link.click();
	                alert('엑셀 다운로드에 성공했습니다');
	            }
	        };
	        xhr.onerror = function() {
	            alert('엑셀 다운로드에 실패했습니다.');
	        };
	        xhr.send();
	    }
	});

profile
공부공부

0개의 댓글