메뉴 건너뛰기

조회 수 586 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

hr(XMLHttpRequest) 객체는 서버와 데이터를 확인하기 위해 사용됩니다.

 

ajax또한 xhr 규격을 사용하여 동작하고 있고, 다양한 메소드를 통해 요청의 상태값이나 시간, 결과, 진행상태 등을 확인 할 수 있습니다.

 

여기서 xhr의 upload.onprogress 메소드를 사용하여 파일의 업로드 진행상황을 확인하고 UI적으로 페이지 진행상태를 표현 할 수 있습니다.

 

대량의 파일이나 다중으로 여러 파일을 넘길 때 상태를 알 수 있다보니 아무래도 기다리는데, 도움이 될 것 같습니다.

 

바로 예제를 통해 확인해 보겠습니다.

 

xhr.upload.progress

사용법 ajax로 넘길때 xhr메소드를 추가하고 내부에 upload.onprogress메소드를 추가하여 정의하고자 하는 파일 내용을 추가하면 됩니다.

xhr: function(){
	var xhr = $.ajaxSettings.xhr();
	xhr.upload.onprogress = function(e){
		var per = e.loaded * 100 / e.total;
		console.log(per);
	};
	return xhr;
},

 

 

사용예제

fileupload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<style>
	*{margin:0;padding:0}
	.progressContainer{position:relative;width: 450px;padding:20px 10px;border: 1px solid #eee;margin-top: 15px;background:#000;height:20px;}
	.progress{position:absolute;width: calc(100% - 20px);height: 20px;}
	.progressTotal{background: #5D5D5D;border-radius: 10px;}
	.progressNow{width: calc(0% - 20px);background: #FFF;border-radius: 10px;}
	.progressPer{background: transparent; text-align:center;color:#A6A6A6;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<h1>
	File Upload Test
</h1>

<P>  The time on the server is ${serverTime}. </P>
	<div style="width: 100%;padding: 25px;">
		<form id="fileForm" action="/upload.do" method="post" enctype="multipart/form-data">
			<input type="file" name="uploadFile" multiple>
			<button type="button" id="btn">전송</button>
		</form>
		<div class="progressContainer">
			<div class="progress progressTotal"></div>
			<div class="progress progressNow"></div>
			<div class="progress progressPer">0 %</div>
		</div>
	</div>
</body>
<script>
	$(function(){	
		$("#btn").on("click", function(){
			console.log("click Time : " + new Date);
			
			var form = $("#fileForm")[0];
			var formData = new FormData(form);
			$.ajax({
				type: "POST",
				enctype: 'multipart/form-data',
				url: "/upload.do",
				data: formData,
				processData: false,
				contentType: false,
				cache: false,
				xhr: function(){
					var xhr = $.ajaxSettings.xhr();
					xhr.upload.onprogress = function(e){
						var per = e.loaded * 100 / e.total;
						progressBar(per);
					};
					return xhr;
				},
				success: function (data) {
					console.log("SUCCESS : ", data);
				},
				error: function (e) {
					console.log("ERROR : ", e);
				}
			});
		});
	});
	
	function progressBar(per){
		if(per > 55){
			$(".progressPer").css("color", "#000");
		}
		per = per.toFixed(1);
		$(".progressPer").text(per+" %");
		$(".progressNow").css("width", "calc(" + per + "% - 20px)");
	}
</script>
</html>

btn이라는 버튼을 클릭하면 file에 존재하는 데이터를 넘기고 xhr메소드에 정의된 onprogress 메소드에 의해 결과 값을 노출 하는 예제입니다.

 

 

결과

극단적으로 퍼센트를 잘 보기위해 3천개의 텍스트파일을 업로드하는 테스트를 진행해봤습니다.

 


  1. JS 첵박스 샘플

    Date2019.06.04 Views694
    Read More
  2. 모달 띄우는 코드

    Date2021.03.25 Views657
    Read More
  3. jQuery - checkbox 전체 선택, 해제 기능 및 단일 체크박스가 해제되었을때 전체 선택 해제 하기

    Date2021.03.09 Views613
    Read More
  4. 간단한 마우스 포인터 따라 다니기

    Date2021.03.26 Views594
    Read More
  5. jQuery - ajax xhr을 활용한 파일 업로드 진행 상태 확인하기

    Date2021.03.09 Views586
    Read More
  6. jQuery - 클릭이벤트 동적 처리하기($("").click(), on('click') 차이)

    Date2021.03.09 Views580
    Read More
  7. SELECTBOX MULTIPLE 검색하기

    Date2021.03.26 Views568
    Read More
  8. jQuery - radio, checkBox값 가져오기, 선택하기, 제어 등

    Date2021.03.09 Views543
    Read More
  9. ajax 동기화 처리하기

    Date2021.03.25 Views416
    Read More
  10. Cesium에서 canvas 화면 center 지점의 좌표 취득

    Date2021.03.25 Views370
    Read More
  11. jQuery - 드래그, 리사이즈 이벤트에 따른 영역 침범 막기

    Date2021.03.09 Views363
    Read More
  12. 목록의 체크 선택/해제에 따라 [전체선택] 체크박스를 체크하거나 해제하기

    Date2021.03.25 Views329
    Read More
  13. 최초 접속시 css와 script가 로딩되지 않을때

    Date2021.03.25 Views322
    Read More
  14. 다중 select

    Date2021.03.31 Views316
    Read More
  15. click에 따른 마우스 휠 on off

    Date2021.03.31 Views303
    Read More
  16. jQuery - 드래그앤드롭(DragAndDrop)을 통한 파일 업로드

    Date2021.03.09 Views291
    Read More
  17. fadeIn() , fadeOut() 을 이용한 간단한 자동 그림 전환

    Date2021.03.26 Views285
    Read More
  18. 항상 최신버전으로 사용하기

    Date2021.03.26 Views284
    Read More
  19. 기본 동작 막기

    Date2021.03.25 Views284
    Read More
  20. javascript, jQuery에서 루프 돌리기 예 (for, forEach, each)

    Date2021.03.25 Views276
    Read More
Board Pagination Prev 1 ... 3 4 5 6 7 8 9 Next
/ 9

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved