Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 7기
- updater
- react
- Preview
- 라우팅
- 항해99
- 개발
- 배포
- Github Actions
- CI/CD
- 브라우저 렌더링
- imagePreview
- previousState
- 미리보기
- useEffect
- socket.io
- 후기
- FileReader
- 접근 제한 라우팅
- S3
- qwe
- Redux
- 채팅방
- rendering
- 비동기
- setstate
- route
- 동기
- 스파르타코딩클럽
- routing
Archives
- Today
- Total
삐옹
업로드 할 파일의 이미지 미리보기 본문
서론
진행 중인 프로젝트에 업로드 할 파일의 이미지를 미리보여주는 기능을 넣어 보고싶어서 내용을 알아보다가,
단순히 코드 복붙을 하고 싶지않아 정리하게 되었다.
Web API 인 FileReader라는 객체를 이용하여 구현해보았다.
React에서 이미지 미리보기
마크업
...
const [imgSrc, setImgSrc] = useState("");
return(
<div>
<Label htmlFor="input-file" className="img_label">
이미지업로드
{imgSrc && <img src={imgSrc} alt="preview-img"></img>}
<FileInput
multiple
type="file"
accept="image/*"
id="input-file"
style={{ display: "none" }}
onChange={(e) => {
encodeFileToBase64(e.target.files[0]);
}}
/>
</Label>
</div>
</Label>
)
...
동작원리
- onChage함수 안에서 e.target.files를 콘솔에 찍어보면 선택된 파일의 목록(FileList)이 나온다
- fileList를 자바스크립트에서 파일에 접근할 수 있도록 한다
- file 객체를 읽어서 base64로 인코딩하여 state안에 넣어준다.
FileReader
FileReader는 file, blob 객체를 다루는 그런 도구. file, blob 객체를 이용해 특정 파일을 읽어 자바스크립트에서 접근할 수 있도록 돕는다.
기본적으로 eventTarget을 상속받았기에 이벤트리스너 부착이 가능하다.
fileReader.readAsDataURL()
base64로 인코딩한 문자열을 FileReader 인스턴스의 result라는 속성에 담는다.
즉 reader.result 하면 자스에서 사용 가능한 해당 이미지의 url이 뜬다.
reader.onload
FileReader가 성공적으로 파일을 읽어들였을 때 트리거되는 이벤트 핸들러.
여기서 state값을 업데이트 해주면 된다.
로직
const encodeFileToBase64 = (fileBlob) => {
const reader = new FileReader();
reader.readAsDataURL(fileBlob);
console.log(reader);
return new Promise(() => {
reader.onload = () => {
setImgSrc(reader.result);
};
});
};
전체코드
...
const [imgSrc, setImgSrc] = useState("");
const encodeFileToBase64 = (fileBlob) => {
const reader = new FileReader();
reader.readAsDataURL(fileBlob); // js에서 사용가능한 이미지 url를 reader 객체에 result 속성에 집어넣을게!
return new Promise(() => {
reader.onload = () => {
setImgSrc(reader.result);
};
});
};
return(
<div>
<Label htmlFor="input-file" className="img_label">
이미지업로드
{imgSrc && <img src={imgSrc} alt="preview-img"></img>}
<FileInput
multiple
type="file"
accept="image/*"
id="input-file"
style={{ display: "none" }}
onChange={(e) => {
encodeFileToBase64(e.target.files[0]);
}}
/>
</Label>
</div>
</Label>
)
...
참고
https://nukw0n-dev.tistory.com/30#FileReader-readAsDataURL--
리액트에서 이미지 미리보기 만들어보기 (React Image Preview)
서론 HTML의 input 태그로 이미지를 핸들링할 때 현재 선택한 이미지를 미리 보고 싶은 경우가 있다. 라이브러리를 통해 구현할 수도 있지만 어떤 방식으로 구현할 수 있을까 고민해보았다. Web API
nukw0n-dev.tistory.com
'React' 카테고리의 다른 글
[채팅 웹 사이트 구현 #1] WebSocket과 Socket.io (0) | 2022.06.26 |
---|---|
살려줘.. Cannot read properties of undefined (0) | 2022.06.22 |
프론트에서 안전하게 로그인 요청하기(feat. 리액트) (0) | 2022.06.19 |
state 불변성을 지켜라(댓글 달기) (0) | 2022.06.16 |
Redux + Firebase 게시글 화면에 뿌려주기(실패ver.) (0) | 2022.06.10 |