[springboot] 다중 MultipartFile, DTO 동시 요청 처리

vector13·2022년 10월 29일
0

1 요구사항 항목

  1. 게시글 등록 api에서 이미지가 여러 장 삽입된다.
  2. 이미지들은 순서가 있다

참고사항

이미지는 s3에 올라가 url 형태로 변환되어 db에 저장된다.


이미지의 순서가 있기 때문에 처음에 생각한 request 의 모습이

이렇게 생겨야 한다고 생각했는데, 저 방식으로 postman이나 swagger에서 테스트하는 방법을 못찾아서

s3에 올라가는 순서가 업로드 순서와 정말 다른지 보기 위해서 도전적으로 img_rank를 제외하고 진행해보았다.

그러므로 구현하려는 요청 request는 이렇게 생겼다.

2 구현

다중 file과 dto를 동시에 요청하기 위해서는 @RequestPart을 이용한다.

 @Operation(summary = "31-1 게시글 작성 ", description = "게시글 작성  API")
    @PostMapping("/posting/{userIdx}")
    public ResponseEntity<?> uploadPost(@PathVariable(value = "userIdx") Long userIdx,
                                           @RequestPart (value= "multipartFileList", required = false) List<MultipartFile> multipartFileList,
                                           @RequestPart(value="posting") PostingDto postingDto ) throws IOException {
 ... controller 로직 .. 

처럼 RequestPart를 이용해서 MultipartFile을 List형태로 받고 DTO도 받을 수있다.
PostingDto 는 inner class로 넣었다.

@Data
    static class PostingDto {
        private String title;
        private String content;
    }

RequestPart의 value 에 해당하는 값을 Postman에서 key에 넣으면 된다.

List< MultipartFile>

postman에서 form-data를 누르고

같은 key의 이름으로 되어있으면 자동으로 리스트로 들어간다.

DTO

dto의 경우에는 content-type을 명시해주어야한다.

3 결과


200 OK 가 뜨고
db에도 정상적으로 들어가있고

s3 버킷에 들어가봐도 내가 넣은 순서대로 들어가있었다.

휴.. 다행이다

4 에러

구현을 진행하다가 403 에러에서 벗어날 수가 없었는데 이는
spring security의 csrf 문제로

SecurityConfiguration 클래스에서 csrf().disable()을 진행해줘야한다.

@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http.cors().and().httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/swagger-ui/**").permitAll()
                .antMatchers("/v3/api-docs/**").permitAll();

    }
}
profile
HelloWorld! 같은 실수를 반복하지 말기위해 적어두자..

0개의 댓글

관련 채용 정보