How do you Create a Download Link in HTML?

Creating a download link in HTML is simpler, thanks to the download attribute. This attribute allows to specify that the linked file should be downloaded rather than opened in the browser. Here’s a modern and effective way to set up a download link.

Using the download Attribute

Here are different scenarios where you can use it to create a download link.

1. With a Direct Link

The download attribute can be added to an <a> (anchor) element to prompt the browser to download the file instead of navigating to it. Here’s how you can use it:

<a href="http://example.com/files/myfile.pdf" download="MyFile.pdf">Download My File</a>

2. With a Blob

If you have data that you want to offer for download without a direct file link, you can use the Blob object and a URL created with URL.createObjectURL(). This method is useful for generating downloadable content on the fly.

<a id="downloadLink" href="#" download="example.txt">Download Example File</a>
<script>
// Create a Blob with some text data
const textData = "Hello, world!";
const blob = new Blob([textData], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
// Set the href attribute of the download link to the Blob URL
document.getElementById('downloadLink').href = url;
</script>

3. With a Data URL

A data URL allows you to embed small files directly within your HTML, bypassing the need for a separate file. Here’s how you can use data URLs for downloads:

<a id="downloadLink" href="#" download="image.png">Download Example Image</a>
<script>
// Create a data URL for an image (base64 encoded PNG)
const imageData = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgAAAABJRU5ErkJggg==";
// Set the href attribute of the download link to the data URL
document.getElementById('downloadLink').href = imageData;
</script>

Handling Different Scenarios

  • For same-origin URLs: The download attribute works seamlessly with direct links.
  • For blobs and data URLs: The download attribute also works well. Just make sure to use URL.createObjectURL() it for blobs and ensure that the data URL is correctly formatted.

Conclusion

Whether using direct links, blobs, or data URLs, creating download links in HTML is simple and easy. The download attribute, combined with JavaScript techniques, allows you to offer files for download dynamically and efficiently. Happy Coding!!!

Learn more How do you Create a Download Link in HTML?

Leave a Reply