工夫/JAVASCRIPT+JQUERY
[jQuery] 다중업로드시 파일정보 다루기
휘현아빠
2021. 5. 16. 12:52
<script>
//첨부파일
$('.input_file').each(function(){
$('.input_file').change(function (e) {
var index = $(this).index();
console.log(e.target.files[0].name);
console.log(e.target.files[0].size);
var i = $(this).val();
var name = $(this).attr('name');
var size = $(this).attr('data-size');
//$('input[name='+name+'_text]').val(i);
//$(this).find('.upload_text').text(i);
$('.upload_'+name).text(e.target.files[0].name);
$('.upload_'+size).text(e.target.files[0].size/1000+"KB");
});
});
</script>
each();
jQuery를 사용해 배열을 관리하고자 할 때 each() 메서드를 사용할 수 있다.
each() 메서드는 매개 변수로 받은 것을 사용해 for in 반복문과 같이 배열이나 객체의 요소를 검사할 수 있는 메서드
each()의 2가지 사용타입
// jQuery 유틸리티 메서드
$.each(object, function(index, item){ });
// jQuery 일반 메서드
$(selector).each(function(index, item){ })
※ 상세정보는 별도로 다루기로 함
change()
해당하는 요소의 value에 변화가 생길 경우 이를 감지하여 등록된 callback함수를 동작시킵니다.
해당 코드는 input,textarea,select 태그에 동작합니다.
<script>
$(function () {
var $inputElement = $("input");
$inputElement.change(function() {
alert("파일 첨부가 완료되었습니다.");
})
});
</script>
※ <input type="file" value=""> 태그에서 파일이 첨부되면 value값에 변화가 생겨 change()가 동작한다.
※ 상세정보는 별도로 다루기로 함
e.target.files
e.target은 이벤트가 일어난 대상, 즉 input 자신을 뜻함
files 파일에 대한 정보가 아래와 같이 배열형태의 객체로 생성시킴
name: 'zerocho.png', // 파일 이름
size: 74120, // byte 단위 파일 크기
lastModified: 1495791249810, // 올린 시간 timestamp
type: 'image/png'
※ e.target.files[0].name 은 each(), index()를 통해 얻어낸 첫째 데이터의 첫번째 항목의 값, 즉 name의 값을 뜻한다.