Home > front end >  How to download files from google cloud storage to user pc (React)
How to download files from google cloud storage to user pc (React)

Time:09-13

I have files on google cloud storage and i want to add a button so that users can download those files to their pc. I tried the usual:

<a href="imageUrlHere" download="testImage">Download</a>

But it only opens the image file in the same tab.

Everything running on the front end of the app by the way.

CodePudding user response:

Since you already have the download URL of the File stored in Cloud Storage, the following function will do the trick:

triggerBrowserDownload(url) {
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName);
  link.setAttribute('target', 'new');
  document.body.appendChild(link);
  link.click();
}

And you can call it with

<a onclick=triggerBrowserDownload("imageUrlHere")>Download</a>

Or, better, by adding a listener:

HTML

<a id="urlLink" url="imageUrlHere">Try it</a>

JavaScript

document.getElementById("urlLink").addEventListener('click', triggerBrowserDownload);

triggerBrowserDownload(evt) {
  const link = document.createElement('a');
  link.href = evt.target.attributes.value.url;
  link.setAttribute('download', fileName);
  link.setAttribute('target', 'new');
  document.body.appendChild(link);
  link.click();
}

CodePudding user response:

An alternative to using HTML attributes would be to set the Content-Disposition header to attachment; filename="file.ext" so you can use the downloadURL so whenever the URL is opened in new tab, it'll be downloaded. This can be set in the metadata when uploading the file or you can use updateMetadata() function to add it for existing files.

const storageRef = ref(storage, 'image.png')

// Adding metadata while uploading files
await uploadBytes(
  storageRef,
  file,
  {
    contentDisposition: `attachment; filename="${file.name}"`,
  }
)

// Updating metadata for existing files
await updateMetadata(storageRef, {
  contentDisposition: 'attachment; filename="image.png"',
})

You just need to redirect the user to a new tab. If you don't specify the filename, the browser will prompt user to enter one.

<a href="URL_FROM_FIREBASE" target="_blank">Download</a>
  • Related