Skip to content

feature/ File 테스트 #84

Description

@blcklamb

주제

BE로 보내는 file 형태 관련 이슈 정리

상황 01

formData에다가 key: 'file', value: png(string) + header-content: multipart/form-data

  const onClickSubmit = async (png: string) => {
    const formData = new FormData();
    formData.append("file", png);
    try {
      await axios
        .post("/api/coupon", formData, {
          headers: { "Content-Type": "multipart/form-data", charset: "utf-8" },
        })
        .then(data => console.log(data));
    } catch (err) {
      console.error(err);
    }
  };

결과물

{
    "timestamp": 1689925177251,
    "message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!",
    "details": "uri=/coupon"
}

문제 원인

query param을 제대로 설정하지 않음

해결

//현재의 경우 html을 png로 변환하는 라이브러리를 써서 png라 명명했음
// e.target.files[0]로 접근하여 append하는 것이 정석
  const onClickSubmit = async (png: string) => {
    const formData = new FormData();
    formData.append("file", png);
    try {
      if (targetId) {
        // api 별 설정에 맞게 query, body(현 api 경우 body key값이 file이기 때문에 위에서 ('file', png)로 append 설정
        const params = new URLSearchParams({ targetId }).toString();
        await axios.post(
          `/api/coupon?${params}`,
          { formData },
         // header content-type 설정 잊지말기 ⭐️⭐️⭐️
          {
            headers: {
              "Content-Type": "multipart/form-data",
              charset: "utf-8",
            },
          },
        );
      }
    } catch (err) {
      console.error(err);
    }
  };

response 캡쳐

image image image

참고

Metadata

Metadata

Assignees

Labels

feature새 기능 추가

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions