본문 바로가기
TIP)

JavaScript) input type="file" UI 커스텀하기 및 파일명 출력하는법

by 모리야의 잡다한 블로그 2023. 1. 18.
728x90
반응형

1. JSP

 

=> input file 선언 및 label로 input file 연동

<label for="file">
  	<div class="btn-upload">파일 업로드하기</div>
</label>
	<input type="file" name="file" data-ax-path="file" id="file" class="form-control" width="80%">
	<p id="originName" style="display : inline-block"></p>

 

 

2. CSS

 

=> input file을 깔끔하게 커스텀하기위한 CSS 소스

 <style>
.btn-upload {
  width: 130px;
  height: 27px;
  background: #fff;
  border: 1px solid rgb(77,77,77);
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  &:hover {
    background: rgb(77,77,77);
    color: #fff;
  }
}

#file {
  display: none;
}
</style>

 

 

3. JS

 

=> 파일첨부 즉 change 시 발생하는 함수

window.onload=function(){
	target=document.getElementById('file'); // file 아이디 선언
	target.addEventListener('change',function(){ // change 함수
		
		if(target.value.length){ // 파일 첨부인 상태일경우 파일명 출력
			$('#originName').html(target.files[0].name);
		}else{ //버튼 클릭후 취소(파일 첨부 없을 경우)할때 파일명값 안보이게
			$('#originName').html("");
		}
		
	});
}

 

 

결과 화면

 

파일 첨부시 파일명과 확장자를 띄워준다.

 

 

해당 1,2,3번을 복사붙여넣기를 사용하시면 됩니다.

728x90
반응형

댓글