2

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.

1 Answer 1

4

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(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Renaud, thank you for your answer. Unfortunately this just open the image in a new tab instead.
this is the a element that was created with your code: <a href="https://..." download="test.png" target="new"></a>
Oh, I see... I use this code to download PDFs and Word documents stored in Cloud Storage and in this case the download opening dialog box is opened. With an image the behaviour is different, which makes sense... I'll delete this answer in few minutes. I'll try to find another way and may post a new answer.
Hi Renaud I was able to adjust your code and find a solution. I'll update my answer with it and accept your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.