Search code examples
firebasevue.jsgoogle-cloud-platformgoogle-cloud-storagefirebase-storage

Download image from firebase storage web - vuejs


I'm trying to implement a download button on a image that will download the image. Since the image is hosted on Firebase Storage, I'm using a variant of their code for retrieving files that I found on the official doc: https://firebase.google.com/docs/storage/web/download-files#download_data_via_url

I changed it a bit since in the example, the code is retrieving the file url from it's path on the bucket while in my case I already know the url:

download(url) {
  const xhr = new XMLHttpRequest();
  xhr.responseType = "blob";
  xhr.onload = () => {
    xhr.response;
  };
  xhr.open("GET", url);
  xhr.send();
},

Now the issue is that the request get's the image but the download (to the user's machine) is not triggered:

enter image description here

I know I'm really close, how do I trigger the picture download? Furthermore, Do I actually need to call it from firebase since the image is already displaying in the website?

Solution:

Thanks to Renaud for the help, I was able to fix my code:

    download(url) {
      const xhr = new XMLHttpRequest();
      xhr.responseType = "blob";
      xhr.onload = () => {
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL(xhr.response);
        const link = document.createElement("a");
        link.href = imageUrl;
        link.setAttribute("download", "test");
        link.setAttribute("target", "new");
        document.body.appendChild(link);
        link.click();
      };
      xhr.open("GET", url);
      xhr.send();
    },

Please feel free to post optimisations to this solution.


Solution

  • One possible approach is to create an hidden link in the page and simulate a click on this link as follows:

    // Get the URL. You have it since you call download(url)
    // In case you don't have the URL, use const url = await getDownloadURL(fileRef);
    const url = ...
    
    
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    link.setAttribute('target', 'new');
    document.body.appendChild(link);
    link.click();