Spring

[Spring] Controller에서 MultipartFile로 파일 받기 (다른 값들과 함께 받는 방법)

2022. 11. 1. 13:47
728x90

FE: Nuxt(Vue)

FE에서 등록할 때 등록할 값들과 사진이 함께 전달됨 (multipart/form-data)

(this.$axios.post(
('https://'),
formData,
{
  withCredentials: true,
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: // token
  }
}
)
).then(res => {
}).catch((error) => {
window.alert(error.response.data.message)
})

 

formData 만드는 법

const formData = new FormData()

formData.append(key, value)

 

** 사진을 여러장 보낼 때

this.files.map((file) => {
    formData.append('image', file)
})

 

BE: Spring

 

Controller에서 FormData를 RequestBody로 받을 수 없다. RequestBody는 String만 처리 가능하기 때문

1. RequestPart 사용

2. ModelAttribute 사용

 

RequestPart

    @PostMapping(value = "/test")
    public ResponseEntity register(@RequestPart Params params,
                                   @RequestPart MultipartFile images) {
        return ResponseEntity.status(HttpStatus.OK).body(1);
    }
public class Params {
    String name;
    Integer price;
}

 

 

ModelAttribute

    @PostMapping(value = "/test")
    public ResponseEntity register(@ModelAttribute Params params) {
        return ResponseEntity.status(HttpStatus.OK).body(1);
    }
public class Params {
    String name;
    Integer price;
    MultipartFile image;
}

 

 

참고

https://gaemi606.tistory.com/entry/Spring-Boot-multipartform-data-%ED%8C%8C%EC%9D%BC-%EC%97%85%EB%A1%9C%EB%93%9C-React-Axios-REST-API

https://minholee93.tistory.com/entry/Spring-Json-with-MultipartFile

728x90

'Spring' 카테고리의 다른 글

[ERROR] Port already in use: 1099  (0) 2022.11.17
no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)  (0) 2022.10.12
BeanDefinitionStoreException: Failed to parse configuration class  (0) 2022.09.14
DTO, VO, Entity  (0) 2022.09.07
Builder 패턴  (0) 2022.09.02
'Spring' 카테고리의 다른 글
  • [ERROR] Port already in use: 1099
  • no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
  • BeanDefinitionStoreException: Failed to parse configuration class
  • DTO, VO, Entity
mean-ji
mean-ji
mean-ji
저년차 기록들
mean-ji
전체
오늘
어제
  • 분류 전체보기 (104)
    • 소개 (1)
    • Server (25)
      • DevOps (9)
      • Database (4)
    • Spring (11)
    • Spring Boot (0)
    • Java (6)
    • Kotlin (3)
    • Vue.js (12)
      • Nuxt (12)
    • Node.js (3)
      • Express (2)
    • Python (9)
      • Flask (2)
    • Git (9)
    • IDE & Tool (4)
    • TIL (16)
    • 생각 (2)
    • 토스 (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

hELLO · Designed By 정상우.
mean-ji
[Spring] Controller에서 MultipartFile로 파일 받기 (다른 값들과 함께 받는 방법)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.