개발 무지렁이

[Spring Boot] 프로필 이미지 노출 본문

Backend/스프링부트

[Spring Boot] 프로필 이미지 노출

Gaejirang-e 2022. 12. 8. 14:58

업로드한 파일을 웹서버에서 접근가능하도록


[WebMvcConfig.java]

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Value("${custom.genFileDirPath}")
    private String genFileDirPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/gen/**")
            .addResourceLocations("file:///" + genFileDirPath + "/");
    }
}

로그인된 회원의 프로필 이미지 노출


[HomeController.java]

@Controller
@RequiredArgsConstructor
public class HomeController {
    private final MemberService memberService;

    @RequestMapping("/")
    public String main(Principal principal, Model model) {
        Member loginedMember = null;
        String loginedMemberProfileImgUrl = null;

        if(principal != null && principal.getName() != null) {
            loginedMember = memberService.getMemberByUsername(principal.getName());
        }

        if(loginedMember != null) {
            loginedMemberProfileImgUrl = loginedMember.getProfileImgUrl();
        }

        model.addAttribute("loginedMember", loginedMember);
        model.addAttribute("loginedMemberProfileImgUrl", loginedMemberProfileImgUrl);

        return "home/main";
    }
}

[Member.java]

@Entity
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@ToString(callSuper = true)
public class Member extends BaseEntity {
    @Column(unique = true)
    private String username;
    private String password;
    private String email;
    private String profileImg;

    public String getProfileImgUrl() {
        if ( profileImg == null ) return null;

        return "/gen/" + profileImg;
    }
}

[main.html]

<html lang="ko"
      xmlns:th="http://thymeleaf.org"
>
<header th:if="${loginedMember != null}">
    <h2>[[${loginedMember.username}]]</h2>
    <img th:src="@{${loginedMemberProfileImgUrl}}" width="150px" style="object-fit:cover;border-radius:10px;" alt="">
</header>

<hr>
<div>안녕하세요</div>
Comments