Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

짱이 될거야

Firebase Web: URL로 이미지 다운로드하기 본문

프로젝트

Firebase Web: URL로 이미지 다운로드하기

jeong57 2022. 8. 12. 20:00

프로젝트 진행 중 Firebase에 올린 이미지를 가져와야 하는 부분이 있었다.

listAll과 getDownladURL을 활용해서 이미지 URL을 가져와 화면에 출력했고, 거기에다가 저장 버튼을 추가해 버튼을 누르면 이미지가 로컬에 저장되게 하는 기능을 추가하고자 했다.

 

https://firebase.google.com/docs/storage/web/download-files#web-version-9_2

 

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

의견 보내기 웹에서 Cloud Storage로 파일 다운로드 Firebase용 Cloud Storage를 사용하면 Firebase에서 제공하고 관리하는 Cloud Storage 버킷에서 파일을 빠르고 손쉽게 다운로드할 수 있습니다. 참고: 기본적

firebase.google.com

Firebase 공식 문서를 참고했는데, 먼저 URL은 이미 구해왔기 때문에 참조 부분은 건너 뛰었다.

그 다음은 URL로 다운로드하기였는데 공식 문서에 나와있는 코드는 아래와 같다.

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

 

위 부분을 그대로 타이핑 했는데, CORS 에러가 났다. 그것 또한 공식 문서에 나와있었고, 추가로 참고한 사이트는 아래와 같다.

https://stove99.github.io/etc/2021/06/09/firebase-storage-cors-setting/

 

Firebase Storage CORS 설정하기

Firebase Storage 에 저장된 이미지를 base64 인코딩 할려고 fetch() 메소드로 이미지 데이터를 가져오려고 했으나 CORS 오류가 났다.

stove99.github.io

이렇게 하고 나니까 더이상 CORS 에러는 나오지 않았지만 그렇다고 해서 어떠한 반응이 나오지도 않았다.

또 하나 더 의문인 것은 아래 코드처럼 blob 변수를 설정해놓고 쓰지 않았다는 것이었다.

const blob = xhr.response;

 

따라서 공식 문서의 코드에 빠진 부분이 있다고 생각을 해서, 구글링을 더 해봤고 아래 질의응답을 통해 그 답을 찾았다.

https://stackoverflow.com/questions/45453470/firebase-download-image-using-download-url-without-calling-storage

 

Firebase Download Image using Download URL (Without Calling Storage)

Firebase's documentation covers downloading an image if you call storage and getDownloadURL, and I have this working fine (straight from the docs): storageRef.child('images/stars.jpg').getDownload...

stackoverflow.com

var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
  var a = document.createElement('a');
  a.href = window.URL.createObjectURL(xhr.response);
  a.download = "fileDownloaded.filetype"; // Name the file anything you'd like.
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
};
xhr.open('GET', url);
xhr.send();

먼저 이미지 URL이 필요하고, XMLHttpRequest()를 사용한다.

response type은 "blob"인데, XMLHttpRequest에서 응답에 포함된 데이터 유형을 지정하는 문자열로 이진 데이터를 포함하는 개체이다.

그 다음에는 'a' tag를 만들고 거기에 URL을 넣고 다운로드 하는 과정인 것 같다.

이 때, a.download = "" 부분을 쓰지 않으면 파일이 다운로드 되지 않는다.

그 다음 open, send 과정을 통해 로컬에 저장되는 것 같다.

 

이렇게 해서 Firebase에 올린 이미지를 받아오고 -> 화면에 띄우고 -> 내 컴퓨터에 저장하는 기능까지를 성공했다.

참고로 프로젝트 코드는 아래와 같다.

function storeImg() {
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
      const blob = xhr.response;
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = "photo";
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
    };
    xhr.open('GET', imgURL);
    xhr.send();
  }

 

Comments