메뉴 건너뛰기

조회 수 601 추천 수 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. .attr() : 태그의 속성 값을 읽어오거나 속성을 추가및 재설정

    Date2019.01.16 Views962
    Read More
  2. .removeAttr() : 특정 속성을 제거

    Date2019.01.16 Views1021
    Read More
  3. //ex)텍스트 박스 포커스 활성, 비활성 이벤트

    Date2019.06.04 Views812
    Read More
  4. 3D Perspective Carousel with jQuery and CSS3 - CSSSlider

    Date2018.11.07 Views1388
    Read More
  5. ajax 동기화 처리하기

    Date2021.03.25 Views416
    Read More
  6. ajax 아작스 통신

    Date2016.09.09 Views8046
    Read More
  7. Ajax 파일 업로드 샘플 코드

    Date2017.03.11 Views7791
    Read More
  8. Ajax를 이용한 데이터 조회시 로딩 로딩 이미지 보이기(jquery이용)

    Date2016.12.22 Views10746
    Read More
  9. Ajax를 통해 전송된 데이터를 Controller에서 List 객체로 받기

    Date2021.03.25 Views12265
    Read More
  10. attr() - style의 특정 속성만 바꾸기

    Date2021.03.26 Views1131
    Read More
  11. before / after / insertBefore / insertAfter - element 추가 (동등 관계)

    Date2021.03.31 Views168
    Read More
  12. bxslider 멈춤현상

    Date2016.12.22 Views10116
    Read More
  13. Cesium에서 canvas 화면 center 지점의 좌표 취득

    Date2021.03.25 Views374
    Read More
  14. change 전의 값을 가져오기

    Date2021.03.26 Views259
    Read More
  15. click event scroll

    Date2021.03.31 Views827
    Read More
  16. click에 따른 마우스 휠 on off

    Date2021.03.31 Views305
    Read More
  17. CSS로 요소에 대한 클릭 등 이벤트 발생을 막고 싶을 때

    Date2021.03.25 Views208
    Read More
  18. datepicker, onclick 이벤트시에 한번에 뜨게 하기

    Date2021.03.26 Views1468
    Read More
  19. DateTimepicker ( Timepicker + Datepicker )

    Date2021.03.26 Views792
    Read More
  20. document.getElementById() 처럼 DOM 객체 얻기

    Date2016.09.21 Views6810
    Read More
Board Pagination Prev 1 2 3 4 5 6 7 8 9 Next
/ 9

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved