본문 바로가기

포트폴리오 만들기/spring boot, jpa emo 기록하기

6일차

반응형

* 파일 업로드 기능

1. application.yml 

spring:
  ...
  # application.yml
  file:
    upload-dir: C:/uploads/

에러 : Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileService': Injection of autowired dependencies failed

=> spring: 아래가 아니라, 완전히 별도로 나와야 해!

spring:
  ...
  
# ⚠️ 여기서부터는 spring 바깥!
file:
  upload-dir: uploads/

 

2. 그다음 로컬 C:/upload 폴더를 미리 직접 만들어줘.

 

3. FileController, FileService 

4. 테스트

 

* 업로드한 파일을 url로 열기

1. WebConfig

@Configuration // Spring 설정 클래스로 등록하겠다는 의미.
public class WebConfig implements WebMvcConfigurer {
// WebMvcConfigurer: Spring MVC의 설정을 커스터마이징할 수 있는 인터페이스.

    @Override
    // 정적 자원(Resource) 을 어떤 URL로 서비스할지 지정하는 메서드.
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // http://localhost:8080/files/파일명 으로 접근 가능
        registry.addResourceHandler("/files/**")
        // 클라이언트가 http://localhost:8080/files/파일명 으로 요청을 보내면 
        // Spring이 해당 요청을 정적 파일로 처리하게 만들겠다.
                
                .addResourceLocations("file:///C:/uploads/");
                // 실제 파일이 존재하는 물리적 경로.3
                // "file:///"는 로컬 디렉토리
    }
}

🧠 정리하자면

이 코드는 다음과 같은 역할을 해:

🗂️ "내 PC의 C:/uploads/ 폴더에 저장된 파일들을"
🌐 "웹 URL http://localhost:8080/files/파일명 으로 접근 가능하게 해줘"


✅ 예시 상황

  1. 파일 업로드 성공 → C:/uploads/cute.jpg 저장됨
  2. 브라우저에서 → http://localhost:8080/files/cute.jpg 접속
  3. 업로드한 이미지를 바로 볼 수 있음!

 

2. 게시글 등록 시 파일도 함께 업로드하기

- Post 엔티티에 fileName 필드 추가.

- PostService에 파일 이름 받도록 수정.

 public PostResponseDto createPost(PostRequestDto dto, String ipAddress, String fileName) {
        Post post = new Post();
        post.setTitle(dto.getTitle());
        post.setContent(dto.getContent());
        post.setAuthor(dto.getWriter());
        post.setIpAddress(ipAddress); // IP 저장
        post.setFileName(fileName);

        Post saved = postRepository.save(post);
        return new PostResponseDto(saved); // 응답 DTO로 변환
    }

- PostController 작성

- Postman 테스트하기 

=> 415 Unsupported Media Type

🔥 핵심 원인: post 필드에 JSON인데 Content-Type이 지정 안 돼서 application/octet-stream으로 처리됨

Spring은 @RequestPart("post")로 JSON을 받을 때 해당 part의 Content-Type이 application/json 이라고 명시돼야 인식할 수 있어.

 

✔️ 방법 1: post에 Content-Type을 명시 (Postman에서 설정)

  1. form-data에서 post 항목 옆에 "Text" 버튼 누르기
  2. "Text" → "application/json"으로 변경

👉 이렇게 되면 post part가 JSON임을 명시하게 되어 서버가 인식 가능!

 

 

반응형

'포트폴리오 만들기 > spring boot, jpa emo 기록하기' 카테고리의 다른 글

10일차  (0) 2025.04.20
7, 8, 9일차  (0) 2025.04.20
4, 5일차  (1) 2025.04.19
플랜  (0) 2025.04.14
2, 3일차  (0) 2025.04.14