웹에서 Cloud Storage로 파일 다운로드

Firebase용 Cloud Storage를 사용하면 Firebase에서 제공하고 관리하는 Cloud Storage 버킷에서 파일을 빠르고 손쉽게 다운로드할 수 있습니다.

참조 만들기

파일을 다운로드하려면 우선 다운로드할 파일을 가리키는 Cloud Storage 참조를 만듭니다.

Cloud Storage 버킷의 루트에 하위 경로를 추가하여 참조를 만들거나 Cloud Storage의 객체를 참조하는 기존 gs:// 또는 https:// URL로 참조를 만들 수 있습니다.

웹 모듈식 API

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

// Create a reference with an initial file path and name
const storage = getStorage();
const pathReference = ref(storage, 'images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
const gsReference = ref(storage, 'gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
const httpsReference = ref(storage, 'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

웹 네임스페이스화된 API

// Create a reference with an initial file path and name
var storage = firebase.storage();
var pathReference = storage.ref('images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

URL을 통해 데이터 다운로드

Cloud Storage 참조에 대해 getDownloadURL() 메서드를 호출하여 파일의 다운로드 URL을 가져올 수 있습니다.

웹 모듈식 API

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

const storage = getStorage();
getDownloadURL(ref(storage, 'images/stars.jpg'))
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      const blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

웹 네임스페이스화된 API

storageRef.child('images/stars.jpg').getDownloadURL()
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      var blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    var img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

SDK에서 데이터 직접 다운로드

SDK 9.5 이상 버전부터 직접 다운로드할 수 있는 다음과 같은 함수를 제공합니다.

이러한 함수를 사용하면 URL에서 다운로드를 우회하고 코드에 데이터를 반환할 수 있습니다. 이렇게 하면 Firebase 보안 규칙을 통해 보다 세밀하게 액세스를 제어할 수 있습니다.

CORS 구성

브라우저에서 바로 데이터를 다운로드하려면 교차 출처 액세스 공유(CORS)가 가능하도록 Cloud Storage 버킷을 구성해야 합니다. 이렇게 하려면 여기에서 설치할 수 있는 gsutil 명령줄 도구를 사용하면 됩니다.

가장 흔한 시나리오와 달리 도메인에 따라 제한하지 않으려면 cors.json 파일에 다음 JSON을 복사합니다.

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

gsutil cors set cors.json gs://<your-cloud-storage-bucket>을 실행하여 이러한 제한사항을 배포합니다.

자세한 내용은 Google Cloud Storage 문서를 참조하세요.

오류 처리

다운로드 시 오류가 발생하는 이유는 파일이 없는 경우, 사용자에게 파일 액세스 권한이 없는 경우 등 다양합니다. 오류에 대한 자세한 내용은 문서의 오류 처리 섹션을 참조하세요.

전체 예시

다음은 오류 처리가 포함된 다운로드에 대한 전체 예시입니다.

웹 모듈식 API

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

// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

// Get the download URL
getDownloadURL(starsRef)
  .then((url) => {
    // Insert url into an <img> tag to "download"
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

웹 네임스페이스화된 API

// Create a reference to the file we want to download
var starsRef = storageRef.child('images/stars.jpg');

// Get the download URL
starsRef.getDownloadURL()
.then((url) => {
  // Insert url into an <img> tag to "download"
})
.catch((error) => {
  // A full list of error codes is available at
  // https://firebase.google.com/docs/storage/web/handle-errors
  switch (error.code) {
    case 'storage/object-not-found':
      // File doesn't exist
      break;
    case 'storage/unauthorized':
      // User doesn't have permission to access the object
      break;
    case 'storage/canceled':
      // User canceled the upload
      break;

    // ...

    case 'storage/unknown':
      // Unknown error occurred, inspect the server response
      break;
  }
});

Cloud Storage에 저장된 파일의 메타데이터를 가져오거나 업데이트할 수도 있습니다.