🌿SPRING/🌱연습[SPRING]

[SPRING] [AWS] 게시글 이미지 업로드 하기 (2) - 이미지 업로드하기

디카페인라떼 2022. 9. 23. 02:44

게시글을 작성 시 이미지를 삽입이 되도록 로직을 짜보자 👀

 


1.Entity
  • Posting 부분에 이미지를 넣는 게 추가되었으므로 필드도 추가해준다
@Column
private String postImg;
//게시글 작성시
public Posting(PostingRequestDto postingRequestDto, Member member, String postImg) {
  this.title = postingRequestDto.getTitle();
  this.content = postingRequestDto.getContent();
  this.member = member;
  this.postImg = postImg;
  this.likes = 0L;
}

 

2.Service
  • 기존에 있던 Create 부분에 사진을 삽입하는 로직을 추가해주면 된다!
//게시글 작성
@Override
public PostingResponseDto create(PostingRequestDto postingRequestDto, Member member,
    MultipartFile image) {

  String postImg = null; //url받을 변수를 초기화

  if (!image.isEmpty()) {//매개변수로 받은 값이 있으면
    try {
      postImg = s3Upload.uploadFiles(image, "images");//dir name : images에 mulipartfile을 올린다
      System.out.println(postImg);// 확인 차 로그에 찍기..
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  Posting posting = new Posting(postingRequestDto, member, postImg);

  posting = postingRepository.save(posting);//생성한 게시글 db에 저장
  return new PostingResponseDto(posting);
}

🚨if( image != null) 로 들어간 경우 image가 실제로 값이 없어도 임의로 하얀 화면?을 생성해서 넣어준다!

👉 isEmpty로 꼭 확인해주기!

3.Controller
//게시글 작성
@PostMapping("/api/auth/post")
public ResponseDto<PostingResponseDto> create(
    @AuthenticationPrincipal UserDetailsImpl userDetails,
    @RequestPart("data") PostingRequestDto postingRequestDto,
    @RequestPart(required = false) MultipartFile image) {

  PostingResponseDto postingResponseDto;

  try {
    Member member = userDetails.getMember();
    postingResponseDto = postingService.create(postingRequestDto, member, image);

  } catch (Exception e) {
    log.error("error: ", e);
    return new ResponseDto<>(null, ErrorCode.INVALID_ERROR);
  }
  return new ResponseDto<>(postingResponseDto);

}

👉 달라진 것이라곤 매개변수로 이미지를 MultipartFile로 받는 다는 것 뿐..

 


Postman 

👉Controller의 매개변수를 잘 넣어 준다..

🧨 잘못 하면 415 에러가 뜬다 !!

 

👉postImg에 url이 잘 뜬다! 입력했던 파일과 같은 사진이다

 

👉S3에도 잘 들어가 있는걸 확인할 수 있다! 😏