본문 바로가기

백엔드/파이어베이스

파이어베이스 (스토리지) - 앵귤러, 리액트

반응형

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

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

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

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

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

아래와 같이 완성됩니다.

규칙지정

기본적으로 누구나 스토리지의 데이터에 접근, 수정, 삭제가 가능합니다. 세팅의 규칙에서 이러한 설정의 수정이 가능합니다.

예를 들어, 로그인한 유저만 파일업로드가 가능하고 사이즈와 타입의 제한이 있는 경우 아래와 같이 규칙을 수정합니다.

match /{allPaths=**} {
  allow read;
  allow write: if 
  request.auth != null &&
  request.resource.size < <size> && 
  request.resource.contentType.matches('<type>')
}

애플리케이션과 연동하기

앵귤러

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

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

 

Firebase - angular 연결하기

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

jin-co.tistory.com


2. 사용하기

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

// 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();
  }
}

리액트

▶ 파일업로드

파일 업로드에 필요한 서비스 가져오기

import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

스토리지 초기화

const storage = getStorage()

스토리지에 저장할 파일이름 설정

const fileName = '<fileName>'

스토리지 레퍼런스 생성. 매개변수로 스토리지 객체와 경로 사용

const storageRef = ref(storage, 'images/' + <fileName>)

업로드를 수행할 함수 생성

const uploadTask = uploadBytesResumable(storageRef, <file>)

해당 함수에 'state_changed' 이벤트를 활용하여 아래 코드 구현

uploadTask.on('state_changed', 
  (snapshot) => {    
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    switch (snapshot.state) {
      case 'paused':
        console.log('Upload is paused');
        break;
      case 'running':
        console.log('Upload is running');
        break;
    }
  }, 
  (error) => {
    // Handle unsuccessful uploads
  }, 
  () => {
    // Handle successful uploads on complete    
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      console.log('File available at', downloadURL);
    });
  }
);

예시

const storeImage = async (image) => {
  return new Promise((resolve, reject) => {
  const storage = getStorage()
  const fileName = `${auth.currentUser.uid}-${image.name}-${Date.now()}`
  const storageRef = ref(storage, 'images/' + fileName)
  const uploadTask = uploadBytesResumable(storageRef, image)
  uploadTask.on(
    'state_changed',
    (snapshot) => {
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
      switch (snapshot.state) {
        case 'paused':
          break
        case 'running':
          break
        }
      },
      (error) => {
        reject(error)
      },
      () => {
        getDownloadURL(uploadTask.snapshot.ref).then(downloadURL => {
          resolve(downloadURL)
        })
      }
    )
  })
}

const imageUrls = await Promise.all(
  [...images].map(image => storeImage(image))
).catch(() => {  
  return
})

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


참고

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

Upload files with Cloud Storage on Web  |  Cloud Storage for Firebase (google.com)

 

웹에서 Cloud Storage로 파일 업로드  |  Firebase용 Cloud Storage

Google I/O 2023에서 Firebase의 주요 소식을 확인하세요. 자세히 알아보기 의견 보내기 웹에서 Cloud Storage로 파일 업로드 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하

firebase.google.com

 

728x90
반응형