HTMLa tagA download link can be created in several ways:
- Add the download attribute to the a tag so that when the link is clicked it downloads the hyperlink target instead of opening it¹. Example:
<a href="/images/" download="w3logo">Click to download image</a>
- 1
- Add the download attribute to the a tag and set a value to specify the name¹ of the downloaded file. Example:
<a href="/images/" download="">Click to download image</a>
- 1
- Set the Content-Disposition response header on the backend to tell the browser to download the file as an attachment². Example:
<?php
// Set the file name
$filename = "";
// Setting the response header
header("Content-Disposition: attachment; filename=$filename");
// Read the contents of the file and output it
readfile("/images/");
?>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- Use the () method to create a URL to a file object and assign it to the href attribute³ of the a tag. Example:
// Get the file object
var file = document.getElementById("file").files[0];
// Create a URL
var url = URL.createObjectURL(file);
// Get the a tag
var link = document.getElementById("link");
// Set the href attribute
link.href = url;
// Set the download property
link.download = file.name;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
References:
(1) The download attribute of the HTML a tag - thew3school Online tutorials. https:///tags/att_a_download.asp.
(2) Front-end how to download files via a link - Nuggets. /post/7039109468080062500.
(3) HTML a tag links Setting up a click to download a file - CSDN Blog. /Gabriel_wei/article/details/105613874.