#목표

웹페이지에서 파일을 업로드시 얼마나 올렸는지 게이지를 확인할 수 있다.


#구현

기본적으로 업로드 프로그레스바는 jquery에 있는 ajax 를 이용한다.


XMLHttpRequest()에서 upload 이벤트로받는 인자값이 파일의 데이터량을 주는데 이것을 전체크기와 현재 로드된 크기를 나눠서 현재 업로드양을 확인할 수 있다.


업로드와 마찬가지로 다운로드도 똑같이 파일 로드된 크기를 알수있지만 브라우저 자체에서 다운로드받는 기능과 겹치면서 두번다운로드받거나 실제로 파일이 받아지지않고 파일내용만 받는 경우가 보였다. 차후에 개선해야될부분이다.


프로그레스바는 부트스트랩을 활용하여 적용하였다. 


$(document).ready(function(){

$("#progress > span").html("0%");

var formData = document.getElementById('file');
var fileData = null;

formData.addEventListener("change", handleFile, false);

function handleFile(){
fileData = new FormData($("#fileUpload")[0]);
}

$("#fileUpload").submit(function (evt){
evt.preventDefault();

var progressText = $("#progress > span");
var progress = $("#progress");
var upload = $("#upload");

if(fileData != null){
upload.attr('disabled',true);
$.ajax({
xhr : function(){
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = ((evt.loaded / evt.total) * 100).toFixed(1);
//Do something with upload progress

//<![CDATA[
if(parseInt(percentComplete) >= 100){
progressText.html("100% 전송완료");
upload.attr('disabled',false);
}else{
progressText.html(percentComplete + "%");
}
//]]>

progress.css({
width : percentComplete + "%"
});
}
}, false);
return xhr;
},
type : "POST",
url : "/uploadFile.do",
data : fileData,
contentType: false,
processData: false,
success : function(result){

$(location).attr('href',result);

console.log(typeof result);
console.log(result);

}
});
}else{
alert("업로드할 파일을 지정해주세요");
}
});
});


'WEB > JavaScript(jQuery)' 카테고리의 다른 글

동적 리스트 필터  (0) 2017.04.12
Posted by moyaiori
,