본문 바로가기

Backend/Firebase

Firebase Storage (Angular, React)

반응형

파이어베이스 스토리지는 이미지 등 Static 파일을 저장할 때 사용합니다.

파이어베이스 스토리지 사용하기

계정으로 로그인한 뒤 좌측 메뉴에서 'Build' -> 'Storage' 선택 후 열린 화면에서 'Get started'를 누릅니다.

편의를 위해 'test mode'를 선택하고 'next'를 누릅니다.

지역선택 후 'done'을 누르면 (이미 지역이 선택되어 있는 경우 자동을 선택됨)

아래와 같이 완성됩니다.

애플리케이션과 연동하기

앵귤러

스토리지를 사용하기 위해 먼저 앵귤러와 파이어베이스를 연결합니다.

1. 앵귤러에 파이어베이스 연결하기

 

Firebase - angular 연결하기

먼저, 앵귤러 프로젝트 콘솔에서 아래와 같이 @angular/fire 모듈을 설치합니다. ng add @angular/fire 설치를 계속할 건지 물어보는데 'y'를 선택합니다. 사용할 툴들을 물어보는데 필요한 기능을 선택 후

jin-co.tistory.com


다음으로 파이어베이스 스토리지 사용을 위해 파이어베이스에서 스토리지 사용설정을 완료합니다.

2. 파이어베이스 스토리지 설정하기

 

Firebase - Storage

파이어베이스 스토리지는 이미지 등 Static 파일을 저장할 때 사용합니다. 파이어베이스 스토리지 사용하기 계정으로 로그인한 뒤 좌측 메뉴에서 'Build' -> 'Storage' 선택 후 열린 화면에서 'Get started

jin-co.tistory.com


3. 앵귤러에서 사용하기

스토리지 서비스 사용을 위해 아래와 같이 스토리지 모듈을 추가합니다.

// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FileUploadComponent } from './components/file-upload/file-upload.component';
import { environment } from 'src/environments/environment';
import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireStorageModule } from '@angular/fire/compat/storage';

@NgModule({
  declarations: [AppComponent, FileUploadComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireStorageModule, //storage
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

서비스 파일을 추가하고 아래와 같이 스토리지를 가져오고 주입합니다.

// image.service.ts

import { Injectable } from '@angular/core';
import { AngularFireStorage } from '@angular/fire/compat/storage';

@Injectable({
  providedIn: 'root'
})
export class ImageService {  
  constructor(private storage: AngularFireStorage) { }  

  addImage(file:File, filePath:string) {
    this.storage.ref(filePath).put(file)
  }

  getImage() {
    return this.storage.ref('test').getDownloadURL();    
  }
}

▶ 파일업로드

템플릿 파일에서 아래와 같이 input 요소에 change 이벤트를 연결하고 이벤트를 매개변수로 전송

<!-- file-upload.component.html -->

<input type="file" (change)="onImageUpload($event)">

클래스 파일에서 이를 처리하는 기능을 만듭니다. 타입제한이 큰 앵귤러의 특성상 아래와 같이 이벤트 타입으로 받은 뒤 HTML input 요소로 변환 후 가져오는 방식을 사용하였습니다.

// file-upload.component.ts

import { Component, OnInit } from '@angular/core';
import { ImageService } from 'src/app/services/image.service';

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css'],
})
export class FileUploadComponent implements OnInit {
  constructor(private imageService: ImageService) {}

  ngOnInit(): void {}

  onImageUpload(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0];
    const filePath = 'test';
    this.imageService.addImage(file as File, filePath);
  }
}

파이어베이스에서 업로드된 이미지 확인이 가능합니다.

▶ 다운로드

<!-- file-download.component.html -->

<div class="container">
  <button (click)="onDownloadClick()">Download</button>
  <img [src]="imageURL | async" alt="">
</div>
// file-download.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ImageService } from 'src/app/services/image.service';

@Component({
  selector: 'app-file-download',
  templateUrl: './file-download.component.html',
  styleUrls: ['./file-download.component.css'],
})
export class FileDownloadComponent implements OnInit {
  imageURL!: Observable<string>;
  constructor(private imageService: ImageService) {}

  ngOnInit(): void {}

  onDownloadClick() {
    console.log(this.imageService.getImage());
    this.imageURL = this.imageService.getImage();
  }
}

리액트

이상으로 파이어베이스 스토리지에 대해서 알아보았습니다.


참고

angularfire/storage.md at master · angular/angularfire (github.com)

 

GitHub - angular/angularfire: The official Angular library for Firebase.

The official Angular library for Firebase. Contribute to angular/angularfire development by creating an account on GitHub.

github.com

 

728x90
반응형