[Spring Boot] 스프링 이미지 업로드 예제 (0) - 예시 상황, 공통 코드

2024. 9. 2. 15:22· Spring Boot
목차
  1. 1. 예제 프로젝트 설명 
  2. 2. 공통 코드
  3. * 구현한 이미지 업로드 프로젝트 *
  4. 2-1. 공통 의존 라이브러리
  5. 2-2. domain
  6. 2-3. repository
  7. 2-4. service
  8. 2-5. controller
  9. 3. 공통 실행 결과
  10. 3-1. 게시글 작성 (POST localhost:8080/v0/api/posts)
  11. 3-2. 모든 게시글 조회 (GET localhost:8080/v0/api/posts)
  12. 3-3. 특정 게시글 조회 (GET localhost:8080/v0/api/posts/1)

1. 예제 프로젝트 설명 

  • 게시글을 작성하는 기본 CRUD 프로젝트 가정
  • 게시글 작성 시 이미지 업로드를 포함하여 구현하고 싶음

 

2. 공통 코드

  • 이미지 업로드 로직을 제외한 기본적인 게시글 작성, 조회 로직만을 포함

 

* 구현한 이미지 업로드 프로젝트 *

  • 내부 디렉토리에 업로드 https://blogan99.tistory.com/138
  • DB에 이미지 직접 저장 https://blogan99.tistory.com/139
  • 외부 경로에 업로드 https://blogan99.tistory.com/140
  • AWS S3에 업로드 https://blogan99.tistory.com/151

 

2-1. 공통 의존 라이브러리

  • build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.mysql:mysql-connector-j'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

 

  • application.yml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/imageDB
    username: image_user
    password: 1234

  jpa:
    hibernate:
      ddl-auto: create # 처음만 create -> 이후엔 update로 수정

 

2-2. domain

  •  Post
    • 게시글 엔티티에 해당
    • 이미지 업로드 부분은 포함 x
@Entity
@Getter @Setter
@NoArgsConstructor
public class Post {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "post_id")
    private Long id;

    private String title;
    private String content;

    public Post(String title, String content) {
        this.title = title;
        this.content = content;
    }
}

 

  •  PostDto
    • 게시글 작성 시 필요한 DTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PostDto {
    private String title;
    private String content;
}

 

2-3. repository

  •  PostRepository
    • JpaRepository 상속
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}

 

2-4. service

  •  PostService
    • 기본적인 게시글 작성, 조회 로직만 포함
@Service
@RequiredArgsConstructor
public class PostService {

    private final PostRepository postRepository;

    // 모든 게시글 리턴
    public List<Post> findAll() {
        return postRepository.findAll();
    }

    // 특정 게시글 리턴
    public Post findById(Long postId) {
        return postRepository.findById(postId).orElse(null);
    }

    // 게시글 저장
    @Transactional
    public Post save(PostDto postDto) {
        Post post = new Post(postDto.getTitle(), postDto.getContent());
        return postRepository.save(post);
    }
}

 

2-5. controller

  •  PostApiController
    • REST API 사용 방식으로 구현
    • 기본적인 게시글 작성, 조회 로직만 포함
@RestController
@RequiredArgsConstructor
@RequestMapping("/v0/api/posts")
public class PostApiController {

    private final PostService postService;

    // 모든 게시글 조회
    @GetMapping
    public ResponseEntity<List<Post>> findAllPosts() {
        return ResponseEntity.ok(postService.findAll());
    }

    // 특정 게시글 단건 조회
    @GetMapping("/{postId}")
    public ResponseEntity<Post> findPost(@PathVariable("postId") Long postId) {
        Post post = postService.findById(postId);
        return post == null ? ResponseEntity.status(HttpStatus.NO_CONTENT).body(null) : ResponseEntity.ok(post);
    }

    // 게시글 작성
    @PostMapping
    public ResponseEntity<Post> savePost(@RequestBody PostDto postDto) {
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(postService.save(postDto));
    }
}

 

3. 공통 실행 결과

  • Postman으로 결과 확인

 

3-1. 게시글 작성 (POST localhost:8080/v0/api/posts)

 

3-2. 모든 게시글 조회 (GET localhost:8080/v0/api/posts)

 

3-3. 특정 게시글 조회 (GET localhost:8080/v0/api/posts/1)

저작자표시 변경금지 (새창열림)

'Spring Boot' 카테고리의 다른 글

[Spring Boot] 스프링 이미지 업로드 예제 (2) - DB에 이미지 직접 저장  (0) 2024.09.02
[Spring Boot] 스프링 이미지 업로드 예제 (1) - 프로젝트 내부 디렉토리에 업로드  (0) 2024.09.02
[Spring Boot] MapStruct 라이브러리로 엔티티 ↔ DTO 변환 자동으로 매핑하기 (예제 코드)  (0) 2024.08.14
[Spring Boot] 데이터 바인딩 예제 (@RequestParam, @ModelAttribute, @RequestBody)  (0) 2024.08.14
[Spring Boot] 스프링 AOP + 스프링 AOP를 사용한 예외 처리 (@Aspect, @ExceptionHandler, @(Rest)ControllerAdvice)  (0) 2024.08.14
  1. 1. 예제 프로젝트 설명 
  2. 2. 공통 코드
  3. * 구현한 이미지 업로드 프로젝트 *
  4. 2-1. 공통 의존 라이브러리
  5. 2-2. domain
  6. 2-3. repository
  7. 2-4. service
  8. 2-5. controller
  9. 3. 공통 실행 결과
  10. 3-1. 게시글 작성 (POST localhost:8080/v0/api/posts)
  11. 3-2. 모든 게시글 조회 (GET localhost:8080/v0/api/posts)
  12. 3-3. 특정 게시글 조회 (GET localhost:8080/v0/api/posts/1)
'Spring Boot' 카테고리의 다른 글
  • [Spring Boot] 스프링 이미지 업로드 예제 (2) - DB에 이미지 직접 저장
  • [Spring Boot] 스프링 이미지 업로드 예제 (1) - 프로젝트 내부 디렉토리에 업로드
  • [Spring Boot] MapStruct 라이브러리로 엔티티 ↔ DTO 변환 자동으로 매핑하기 (예제 코드)
  • [Spring Boot] 데이터 바인딩 예제 (@RequestParam, @ModelAttribute, @RequestBody)
공대생안씨
공대생안씨
전자공학과 학부생의 코딩 일기
티스토리
|
로그인
공대생안씨
공대생의 코딩 일기
공대생안씨
글쓰기
|
관리
전체
오늘
어제
  • All Categories (153)
    • Spring Boot (46)
      • JPA (7)
      • Lombok (2)
    • Java (21)
    • DevOps (3)
      • CI,CD (8)
      • Monitoring (2)
    • Database (7)
      • MySQL (5)
      • MongoDB (1)
      • H2 (1)
    • Trouble Shooting (5)
    • FE (4)
    • IntelliJ (3)
    • Git (3)
    • Algorithm (41)

블로그 메뉴

  • 홈
  • 태그
  • Github

공지사항

인기 글

hELLO · Designed By 정상우.v4.2.2
공대생안씨
[Spring Boot] 스프링 이미지 업로드 예제 (0) - 예시 상황, 공통 코드
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

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

블로그 게시글

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

모든 영역

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

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