-
[JavaScript] FileReader 객체JavaScript 2022. 9. 11. 19:27
FileReader 객체란
FileReader는 Blob(따라서 File도) 객체에서 데이터를 읽는 것을 목적으로 하는 객체이다.
*blob 객체 : 주로 이미지, 비디오, 사운드 등과 같은 멀티미디어 객체속성
- FileReader.error : 파일을 읽는 도중에 발생한 에러를 나타냄
- FileReader.readyState : FileReader의 상태를 나타내는 숫자
- EMPTY : 0 : 아직 데이터가 로드 되지 않았음.
- LOADING : 1 : 데이터가 로딩 중.
- DONE : 2 : 모든 읽기 요청이 완료됨.
- FileReader.result : 파일의 컨텐츠
이벤트 핸들러
- FileReader.onabort : 읽기 작업이 중단 될 때마다 발생
- FileReader.onerror : 읽기 작업에 에러가 생길 때마다 발생
- FileReader.onload : 읽기 작업이 성공적으로 완료 되었을 때마다 발생
- FileReader.loadstart : 읽기 작업이 시작할 때마다 발생
- FileReader.loadend : 읽기 작업이 성공 or 실패에 상관없이 발생
- FileReader.progress : 읽기 작업 중 발생
주요 메소드
- FileReader.readAsArrayBuffer(blob) : result 속성에 파일의 내용을 나타내는 ArrayBuffer가 포함
- FileReader.readAsText(blob, [encoding]) : result 속성에 파일 내용이 텍스트 문자열로 포함
- FileReader.readAsDataURL(blob) : result 속성에 파일의 내용을 나타내는 data: URL이 포함
- FileReader.abort() : 읽기 요청을 중단
example
<input type="file" onchange="previewFile()" /><br /> <img src="" height="200" alt="이미지 미리보기..." />
const previewFile = () => { const preview = document.querySelector('img'); const file = document.querySelector('input[type=file]').files[0]; const reader = new FileReader(); reader.addEventListener( 'load', function () { preview.src = reader.result; }, false ); if (file) { reader.readAsDataURL(file); } }
반응형'JavaScript' 카테고리의 다른 글
[JavaScript] 특정 요소에 따른 스크롤 자동 조정 : scrollIntoView() (0) 2023.01.03 [JavaScript] checkbox 체크 확인, select, radio 값 가져오기 (0) 2022.10.11 [JavaScript] use strict (0) 2022.08.30 [JavaScript] var let const 차이점 (0) 2022.08.08 [JavaScript] 키보드 이벤트: 특정키 확인 (key, code, keyCode) (0) 2022.07.18