개발 무지렁이

[Spring Boot] 프로필 이미지 제거 본문

Backend/스프링부트

[Spring Boot] 프로필 이미지 제거

Gaejirang-e 2022. 12. 8. 10:09

[MemberController.java]

@Controller
@RequestMapping("/member")
@RequiredArgsConstructor
public class MemberController {
    private final MemberService memberService;

    @PostMapping("/remove/image");
    public String remove(Principal principal) {
        Member member = memberService.getMemberByUsername(principal.getName());
        memberService.removeProfileImg(member);
    }
}

[MemberService.java]

@Service
@RequiredArgsConstructor
public class MemberService {
    private final MemberRepository memberRepository;

    public void removeProfileImg(Member member) {
        member.removeProfileImgOnStorage();
        member.setProfileImg(null);

        memberRepository.save(member);
    }
}

[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 void removeProfileImgOnStorage() {
        if(profileImg == null || profileImg.trim().length() == 0 ) return;

        String profileImgPath = getProfileImgPath();
        new File(profileImgPath).delete();
    }

    private String getProfileImgPath() {
        return AppConfig.GET_FILE_DIR_PATH + "/" + profileImg;
    }
}

[AppConfig.java]

@Configuration
public class AppConfig {
    public static String GET_FILE_DIR_PATH;

    @Value("${custom.genFileDirPath}")
    public void setFileDirPath(String genFileDirPath) {
        GET_FILE_DIR_PATH = genFileDirPath;
    }
}
Comments