React 이미지 업로드시에 Form Data 사용하기

구구·2023년 2월 17일
1
post-thumbnail

🪴 formData 객체

👉 formData 객체는 key, value 형식으로 되어 있는 객체이다.

formData.append('key', value);

👉 FormData 객체는 데이터를 multipart/form-data 형식으로 전송할 수 있다.

const saveFileImage = async e => {
  try {
    const formData = new FormData();  // formData 생성
    formData.append('image', e.target.files[0]);  // 이미지 파일 값 할당
    
    const config = {
      headers: {
        Authorization: ...,  // 토큰 넣어주기
        'Content-Type': 'multipart/form-data',  // 데이터 형식 지정
      },
    };
    // 이미지 업로드 중
    const response = await axios.post(`api url`, formData, config);  // api 통신
    // 이미지 업로드 성공
  } catch (error) {
    // 이미지 업로드 실패
  }
};


🪴 로컬에 있는 이미지를 업로드하기

👉 input 의 type, accept, ref, onChange, style 속성을 이용하여 로컬 이미지 주소 가져오기

import { useRef } from 'react';

const thumbnailInput = useRef();
const saveFileImage... // 생략 위의 코드 참고

<input type='file' accept='image/jpg, image/jpeg, image/png' multiple ref={thumbnailInput} onChange={saveFileImage} />

👉 sytle 속성에 display: none 을 부여하고 button 요소로 커스텀할 수 있다.

const handleClick = () => {
  thumbnailInput.current.click();
};

<button onClick={handleClick}>
  썸네일 업로드
  <input type='file' accept='image/jpg, image/jpeg, image/png' multiple ref={thumbnailInput} onChange={saveFileImage} style={{ display: 'none' }} />
</button>

👉 서버에 formData 전송 후 서버에 등록된 이미지 url 받아오기

const saveFileImage = async e => {
  try {
    const formData = new FormData();  // formData 생성
    formData.append('image', e.target.files[0]);  // 이미지 파일 값 할당
    
    const config = {
      headers: {
        Authorization: ...,  // 토큰 넣어주기
        'Content-Type': 'multipart/form-data',  // 데이터 형식 지정
      },
    };
    // 이미지 업로드 중
    const response = await axios.post(`api url`, formData, config);  // api 통신
    // 이미지 업로드 성공
    dispatch(setWriteContent({ type: 'thumbnail', value: `${response.data.imageUrl[0]}` }));
  } catch (error) {
    // 이미지 업로드 실패
  }
};

👉 서버에서 받아온 이미지 url을 img 태그 src에 부여하여 이미지 보여주기

<img src={`서버에 등록된 이미지 주소`} alt='thumbnail' />

0개의 댓글