Home > Enterprise >  Download image from firebase storage web - vuejs
Download image from firebase storage web - vuejs

Time:11-25

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: 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.

CodePudding user response:

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();
  • Related