@Configuration
@Slf4j
public class FirebaseConfig {
@Bean
public FirebaseApp firebaseApp() throws IOException {
log.info("Initializing Firebase.");
FileInputStream serviceAccount =
new FileInputStream("firebase.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setStorageBucket("heroku-sample.appspot.com") **// storage 주소 입력**
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
log.info("FirebaseApp initialized" + app.getName());
return app;
}
@Bean
public FirebaseAuth firebaseAuth() throws IOException {
return FirebaseAuth.getInstance(firebaseApp());
}
@Bean
public Bucket bucket() throws IOException {
**// Storage Bucket을 Bean으로 등록**
return StorageClient.getInstance(firebaseApp()).bucket();
}
}
setStorageBucket 을 옵션에 추가하여 storage 추소를 입력한다 (gs://를 뺸 주소)Bucket 을 사용할 수 있게 Bean으로 등록한다.@PostMapping("/me/profile")
public User updateProfile(**@RequestParam MultipartFile image,**
Authentication authentication) {
User user = (User) authentication.getPrincipal();
log.info("user: {}", user);
return userService.updateProfile(user, image.getBytes());
}
Firebase Storage 저장 위치를 정하고 가져오게한다.
public User updateProfile(User user, byte[] image) {
// File 저장 위치를 선언
String blob = "/users/"+user.getUid()+"/profile"
try {
// 이미 존재하면 파일 삭제
if(bucket.get(blob) != null) {
bucket.get(blob).delete();
}
// 파일을 Bucket에 저장
bucket.create(blob, image);
// DB에 유저 정보 업데이트 (Profile 이미지 위치 추가)
user.updateProfile("/users/"+user.getUid()+"/profile");
userRepository.save(user);
return user;
} catch (IOException e) {
log.error(user.getUid() + " profile upload faild", e);
throw new CustomException(ErrorCode.IMAGE_UPLOAD_FAILED);
}
}
DB에 유저 profile 주소 추가 예제
저장한 주소로 Image를 가져오는 API를 만들어야한다.
@GetMapping("/users/{uid}/profile")
public byte[] downloadProfile(@PathVariable String uid) {
return userService.getProfile(uid);
}
byte[] 를 통해 파일을 보내줄 수 있다.
Client 에선 <img src=”/users/{uid}/profile”/> 을 통해 가져올 수 있다.
public byte[] getProfile(String uid) {
return bucket.get("/users/"+uid+"/profile").getContent();
}