[react + ts] 이미지 미리보기

young0_0·2023년 6월 30일
0

react

목록 보기
4/7

이미지 미리보기 파일 업로드

파일 업로드

파일을 선택하는 input 창이 안보이게 하고 뒷 배경을 클릭했을 경우 뜨게 하는 방법을 하려고 한다.
css 는 tailwind를 사용 하였다.

<div className="relative flex h-full flex-col items-center  justify-center overflow-hidden rounded-2xl bg-beige">
  <label 
      className="flex h-full w-full cursor-pointer flex-col items-center justify-center">
    <span>사진을 추가해 주세요</span>
    <input  type="file" accept="image/*" />
  </label>
</div>

나중에 input file를 안보이게하고 그 부분에 이미지를 업로드 했을경우 클릭했을 때 이미지 업로드 창이 뜨게 하기 위해 label에 전체를 감쌌다.

input file

  • 저장장치의 파일을 하나 혹은 여러개 선택할수 있다.
  • File API를 사용해 조작할 수 있다.
  • accept: 허용하는 파일 유형을 나타내는 하나이사의 고유한 파일 유형 지정자

이미지 미리보기

이미지를 업로드 하고 미리 보기

//type
export interface EditorDataType {
  file?: string | null;
}
  
const [editorData, setEditorData] = useState<editorDataType>(null)
const fileRef = useRef<HTMLInputElement>(null);

  
//이미지 미리보기
const handleUploadFile = () => {
  const fileImg = fileRef?.current?.files?.[0];
    if (fileImg) {
      const reader = new FileReader();
      reader.readAsDataURL(fileImg);
      reader.onloadend = () => {
        setEditorData(reader.result as string);
      };
    }
  };
  
  //이미지 영역
 <div className="relative flex h-full flex-col items-center  justify-center overflow-hidden rounded-2xl bg-beige">
    <label
       onChange={handleUploadFile}
       className="flex h-full w-full cursor-pointer flex-col items-center justify-center">
              
 		<span className="mt-2">사진을 추가 하세요</span>
      {/* 업로드 된 이미지 */}
 		{file && <img src={file} className="write-img" />}
 		<input
 		 className="hidden"
 		 type="file"
 	 	 accept="image/*"
 	 	 ref={fileRef}
 		/>
   </label>
</div> 

FileReader

File 혹은 Blob 객체를 이용해 파일의 내용을(혹은 raw data버퍼로) 읽고 사용자의 컴퓨터에 저장하는 것을 가능하게 해준다.

FileReader.onload

FileReader가 성공적으로 파일을 읽어 들었을 때 의 이벤트 핸들러

FileReader.readAsDataURL()

File 혹은 Blob 을 읽은 뒤 base64로 인코딩한 문자열을 FileReader 인스턴스의 result라는 속성에 담아준다.
이 메서드를 사용해 우리의 이미지를 base64로 인코딩하여 state 안에 넣어준다.

profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

0개의 댓글