const handleAddFile = (event) => {
const reader = new FileReader();
if (event.target.files[0]) {
reader.readAsDataURL(event.target.files[0]);
}
reader.onloadend = () => {
const base64Src = reader.result;
const imgFile = event.target.files[0];
setPhotoPrevArr([...photoPrevArr, base64Src]);
setPhotoUploadArr([...photoUploadArr, imgFile]);
};
};
FileReader 객체를 이용해야 하고, event 객체를 통해 들어온 파일을 readAsDataURL 함수를 이용해서 읽어야한다.
readAsDataURL 함수는 컨텐츠를 특정 Blob나 File에서 읽어오는 역할을 한다. 읽어오는 작업이 끝나게 되면, readyState의 상태가 DONE이 되고, loadend 이벤트가 트리거되며 base64 인코딩된 데이터가 result에 담기게 된다.
그리고 나서 인코딩된 데이터를 photoPrevArr에 갱신한다. 그리고 아래와 같이 이미지 태그를 생성하여 렌더링하면 된다.
<PhotoPrevBox>
{photoPrevArr.map((item, index) =>
index === 0 ? (
<FirstPrevPhoto>
<img
src={item}
style={{ width: '150px', height: '150px' }}
/>
<div>대표 사진</div>
</FirstPrevPhoto>
) : (
<div>
<img
src={item}
style={{ width: '150px', height: '150px' }}
/>
</div>
)
)}
</PhotoPrevBox>