파일 업로드 구현

히니·2025년 10월 16일

React

목록 보기
2/2

파일 업로드 구현관련해서 바닐라JS와 React 코드를 비교하기로 한다.

가장 먼저, 바닐라JS에서의 코드이다.


function selectImage() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = (e) => {
    const file = e.target.files[0];
    if (file) {
      console.log(file);
    }
  };
  input.click();
}

// 버튼 클릭 시 실행
document.getElementById('uploadBtn').onclick = selectImage;

동적으로 태그를 추가해서 구현하는것이 일반적인 케이스이다.

React에서의 코드는


import { useRef } from 'react';

function ImageUpload() {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 파일 처리 로직
      console.log(file);
    }
  };

  return (
    <div>
      <button onClick={handleButtonClick}>이미지 선택</button>
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileChange}
        style={{ display: 'none' }}
      />
    </div>
  );
}

이떄 브라우저는 client가 서버에게 파일 저장하라고 하기전에 임시로 파일을 메모리에만 임시 보관한다.

profile
안녕하세요

0개의 댓글