[React] Axios / 파일과 객체를 동시에 서버에 전송하기 / FormData

Hyunsu Hera Choi·2022년 8월 9일
3

Axios 설치하기

yarn add axios


Axios Post 요청 기본 폼

        post( 서버URL
            , 보낼data
            , {config 정보...}
            }.then(res => {
            요쳥결과 처리
        }).catch(err => {
            에러처리
        });


FormData에 File객체 및 데이터 추가 방법

FormData는 Key, Value 로 이루어져있다.
Key값을 지정해주고 Value에 Data를 넣어주면 된다.

json 객체를 추가할 때에는

1) 객체를 json으로 파싱하고
2) Blob객체를 생성하고, 파라미터로 위 Json 객체와 json타입이라는 것을 명시한 config를 넣어준다.
//FormData 객체선언
        const formData = new FormData();

//File 추가
        formData.append('file', file);

//객체를 Json타입으로 파싱하여 Blob객테 생성, type에 json 타입 지정
        formData.append('movie', new Blob([JSON.stringify(movie)], {
            type: "application/json"
        }));

FormData에 파일, 객체 추가하여 Post요청 날리기

  • formData에 객체를 추가할 때 JSON으로 파싱한 후, Blob객체를 생성하여 넣어주는 것이 관건이다.
  • axios config에는 context-type을 multipart/form-data 로 지정하기!
new Blob([JSON.stringify(movie)], {type: "application/json"})
import { post } from 'axios';
const handleSubmit = (e) => {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('movie', new Blob([JSON.stringify(movie)], {
        type: "application/json"
    }));

    post('http://localhost:8080/movie'
        , formData
        , {
            headers: {
                "Contest-Type": "multipart/form-data"
            }
        }
    ).then(res => {
        console.log(res);
    }).catch(err => {
        alert('등록을 실패하였습니다.');
    });
}


   }).catch(err => {
        에러처리
    });

0개의 댓글