Input + Output = True

formdata react file upload / 리액트 이미지 전송 본문

🎨FrontEnd/React

formdata react file upload / 리액트 이미지 전송

IOTrue 2023. 2. 8. 21:19

formdata react file upload / 리액트 이미지 업로드 / 리액트 이미지 전송

 

이미지를 서버에 전송하려면 보통 FormData라는 것이 필요하다.

방법은 간단하고, 이전 프로젝트에서 사용한 코드로 설명하겠다.

react + axios를 사용했다.

 

 

1. html 세팅 - 이미지 첨부

<StInput
    className="uploadInput"
    type="file"
    id="image"
    accept="image/*"
    onChange={onChangeFile}
    multiple="multiple"
/>

 

2. react 세팅 - 이미지 FormData 추가

const [fileImg, setFileImg] = useState();

  //formData func;
const formData = new FormData();
const onChangeFile = (e) => {
    encodeFileToBase64(e.target.files[0]);
    const formImg = e.target.files[0];
    setFileImg(formImg);
    formData.append("file", formImg);
};

 

3. html 세팅 - 업로드 버튼

<StForm
  onSubmit={(e) => {
    onWriteHandler(e);
  }}
  ...
>

 

4. react 세팅 - 이미지 업로드 dispatch

 const onWriteHandler = async (e) => {
    e.preventDefault();
    formData.append("image", fileImg);
    formData.append("content", content);
    for (const form of formData) { //formdata console.log 보는 방법
      //console.log("form 최종", form);
    }
    await dispatch(__addPostThunk(formData)) //여기가 서버로 전송하는 dispatch
    .then((res)=>{
      dispatch(__postsMain())
    })
  };

 

5. redux - 서버 전송 API

export const __addPostThunk = createAsyncThunk(
  "ADD_POST",
  async (payload, thunkAPI) => {
    try {
      await api.post( //instance를 사용해서 url이 생략됨
        `posts`, 
        payload, 
        {
          headers: { //headers에 form-data 타입 지정
            "Content-Type": "multipart/form-data",
          },
        }
      )
      return thunkAPI.fulfillWithValue(payload);
    } catch (e) {
      return thunkAPI.rejectWithValue(e);
    }
  }
);

 

즉, formData 에 append 해서 formData를 서버에 전송하는데,

전송하는 header에 form-data 타입을 지정해서 보내면 된다.
끝.

 

 

참고

https://iotrue.tistory.com/entry/%EB%A6%AC%EC%95%A1%ED%8A%B8-axios-instance-interceptor-axios-%EB%AA%A8%EB%93%88%ED%99%94

 

리액트 axios instance & interceptor/ axios 에러 핸들링

😎 리액트 axios instance & interceptor/ axios 에러 핸들링 이번 프로젝트 코드를 예시로 사용하겠다 ✅ axios instance (인스턴스) axios instance는 axios를 사용할 때 공통으로 들어가는 기본 코드를 모듈화 할

iotrue.tistory.com

 

Comments