들어가기전에..
- 약사회원의 회원가입시, 가입할 때 등록한 이미지 파일과 작성한 텍스트를 같이 서버에 전송해야 하는 상황이 생겼다.
- file, json data를 같이 formData로 보내기로 결정!
- 즉 file은 multipart/form-data, data는 application/json 형식으로 보내기 위해 Blob(블랍)을 사용!
- 폼의 각 필드와 값을 나타내는 키/값 쌍들의 집합을 쉽게 구성할 수 있는 방법을 제공
- 데이터를 multipart/form-data 형식으로 전송할 수 있다
- 메서드
- FormData.get() : FormData 객체에서 지정한 키와 연관된 첫 번째 값을 반환
- FormData.append() : FormData 객체의 기존 키에 새 값을 추가하거나, 키가 없는 경우 키를 추가
Blob?
- JavaScript에서 Blob(Binary Large Object, 블랍)은 이미지, 사운드, 비디오와 같은 멀티미디어 데이터를 다룰 때 사용할 수 있다.
내가 작성한 코드
const [businessImgName, setBusinessImgName] = useState<string>("");
const [pharmImgName, setPharmImgName] = useState<string>("");
const onSubmit: any = (e: { preventDefault: () => void; target: any }) => {
e.preventDefault();
const formData = new FormData(e.target);
const email = formData.get(FORM_FIELD_NAMES.EMAIL);
const password = formData.get(FORM_FIELD_NAMES.PASSWORD);
const name = formData.get(FORM_FIELD_NAMES.NAME);
const address = formData.get(FORM_FIELD_NAMES.ADDRESS);
const businessImg: any = formData.get(FORM_FIELD_NAMES.BUSINESSIMG);
const pharmImg: any = formData.get(FORM_FIELD_NAMES.PHARMIMG);
if (!email || !password || !name || !address || !businessImg.name || !pharmImg.name) {
return toast.error("모든 항목을 입력해주세요", {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
}
if (error.email === true || error.password === true || error.name === true) {
return toast.error("항목을 다시 확인해주세요", {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
}
if (checks === false) {
return toast.error("위치정보 사용에 동의해주세요", {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
}
const data = {
name: name,
email: email,
password: password,
address: address,
};
const formDataForsubmit = new FormData();
formDataForsubmit.append("businessCertificate", businessImg);
formDataForsubmit.append("pharmacistCertificate", pharmImg);
formDataForsubmit.append("userSignUpDto", new Blob([JSON.stringify(data)], { type: "application/json" }));
const postSignUp = async () => {
try {
await axios({
url: APIS.POST_PHARM_SIGNUP_JWT,
method: "post",
data: formDataForsubmit,
});
} catch (error: any) {
if (error?.response?.status === 404) {
return toast.error("현재 약국의 주소와 동일한지 확인해주세요.", {
position: "top-center",
autoClose: 1500,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
}
if (error?.response?.status === 409) {
return toast.error("이미 가입된 아이디입니다.", {
position: "top-center",
autoClose: 1500,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
}
console.log(error);
}
navigate("/login");
};
postSignUp();
};