I would like to create a download button in HTML such that if it is clicked, a file will be download from an URL. However, if the URL is not present (it returns a 404 error), it will try to download the file from an alternate link. If the alternate link also fails, do nothing.
Presently, I am using href
attribute of a
tag to create download link.
How to do the above mentioned process with the help of href
attribute?
If it is not possible with href
then what is the procedure to create such a button?
UPDATE:
<a href="downloadlink.com/somefile.exe">Download File</a>
I created a fiddler for you with a proof of concept: http://jsfiddle.net/zbb7j2pq/1/
HTML:
<a id="button" href=""
data-primary-target="http://www1.some-server.example/file"
data-secondary-target="http://www2.some-server.example/file"
data-ternary-target="http://www2.some-server.example/file">
Download
</a>
Script (using the jQuery library in this case for convenience):
$(document).ready(function(){
$('#button').on('click', function(e){
e.preventDefault();
var targets = [
$(e.target).data('primary-target'),
$(e.target).data('secondary-target'),
$(e.target).data('ternary-target')
];
$(targets).each(function(key, target){
$.ajax({
type: 'HEAD',
url: target,
success: function() {
window.location = target;
}
});
});
});
});
If you run that code in the fiddler, then you can see the head requests to the targets inside the network tab of your browsers development console. The actual download does not start due to cross domain issues. That is a separate question, though.
The code allows you to iterate through specified alternatives and execute a routine for each. Inside that routine you could then make a head request and check if it is valid and usable. If so: change the windows location object to it and the download will start. If not just skip to the next alternative.
This should point you into the right direction. But you will have to dig into JavaScript programming a little for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With