[Project] Codetech - 이미지 관련 에러

Heera1·2022년 12월 1일
0

[Project] Codetech

목록 보기
4/7

1. 이미지 파일의 확장자가 blob으로 저절로 바뀌어 보내지는 에러

이미지 파일을 api post 요청으로 서버로 보내면 api 호출에 들어가기 전엔 본래의 이미지 확장자이다가, api 호출 안으로 들어가면 파일의 확장자가 blob으로 저절로 바뀌었다.

도대체 무슨 오류일지 찾아보다가 form.append('', new Blob(...))을 사용한 것이 문제라는 것을 발견했다.


기존 코드

  const handelSubmitThumbnail = async (e: any) => {
    const sizeData = {
      width: 400,
      height: 400,
    };

    e.preventDefault();
    const formData = new FormData();
    formData.append('file', new Blob([thumbnailBase64] as any, { type: 'application/json' }));
    formData.append(
      'request',
      new Blob([JSON.stringify(sizeData)] as any, { type: 'application/json' })
    );
    
    // api 요청
    try {
      const thumbnailPostApi = await selectThumnailImg(formData);
      console.log(`thumbnailPostApi`, thumbnailPostApi);
      setThumnailImg(thumbnailPostApi);
    } catch (err: unknown) {
      console.log(err);
    }
  };


//api 함수
export const selectThumnailImg = async (data: any) => {
  try {
    const thumbnailImg = await axios.post('/api/thumbnail', data);
    return thumbnailImg;
  } catch (err: any) {
    return err.response;
  }
};

수정한 코드

  const handelSubmitThumbnail = async (e: any) => {
    const sizeData = {
      width: 400,
      height: 400,
    };

    e.preventDefault();
    const formData = new FormData();
    formData.append('file', thumbnailBase64); //수정한 부분
    formData.append(
      'request',
      new Blob([JSON.stringify(sizeData)] as any, { type: 'application/json' })
    );
    
    // api 요청
    try {
      const thumbnailPostApi = await selectThumnailImg(formData);
      setThumnailImg(thumbnailPostApi);
    } catch (err: unknown) {
      console.log(err);
    }
  };


//api 함수
export const selectThumnailImg = async (data: any) => {
  try {
    const thumbnailImg = await axios.post('/api/thumbnail', data, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }); //수정한 부분
    return thumbnailImg;
  } catch (err: any) {
    return err.response;
  }
};
profile
웹 개발자

0개의 댓글