파일 업로드 기능 만들기(With Firebase Storage)

Jay·2023년 4월 10일

목적

  • Firebase Storage를 File서버로 이용하여 File을 업로드
  • Firebase Storage를 셋업하는 법을 숙지한다.
  • Form을 이용해 File을 업로드 하는 법을 숙지한다.

Firebase Storage Setup

  1. Storage에 들어가 시작하기를 눌러 스토리지를 만든다.
  2. gs로 시작하는 스토리지 주소를 복사한다.
  3. Config에 Storage를 추가한다.
@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으로 등록한다.

File을 입력받고 저장하기

  • MultipartFile(http form-data)을 통해 이미지등 파일을 받을 수 있다 (JSON으로 전송은 어려움)
@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());
    }
  • Bucket 사용해 저장하기
    • 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를 만들어야한다.

파일 보내주기

  • Controller

@GetMapping("/users/{uid}/profile")
    public byte[] downloadProfile(@PathVariable String uid) {
        return userService.getProfile(uid);
    }

byte[] 를 통해 파일을 보내줄 수 있다.

Client 에선 <img src=”/users/{uid}/profile”/> 을 통해 가져올 수 있다.

  • Service
public byte[] getProfile(String uid) {
    return bucket.get("/users/"+uid+"/profile").getContent();
}

0개의 댓글