Reputation: 650
I want to start file downloading when I clicked the button.
I just have the path of the file.
How can I start downloading?
This is what I tried so far:
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
var do = '<a href="'+ filepath +'" download="file">file</a>';
$(body).append(do);
});
What I am doing wrong.
I never want to redirect the page.
Is downloading start in browser or in software for downloading files if installed on client machine
Upvotes: 3
Views: 25506
Reputation: 1157
You can create a form using jQuery and use the submit function. This will not change the URL in the address bar.
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
var form = $('<form>').attr('action', filepath);
form.submit();
});
Upvotes: 0
Reputation: 59232
If you want to download a file to the client, then do this:
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
location.href = filepath;
});
location.href
will look for a page, but it will not find anything, so it will download the file instead.
Upvotes: 1
Reputation: 8954
Alternatively you can also set the top.location
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
top.location.href = filepath;
});
Upvotes: 6
Reputation: 324630
You cannot force a file to be downloaded in JavaScript.
What you can do is location.href = "somefile.ext";
, however it will only be downloaded if the server includes Content-Disposition: attachment
as one of its response headers to that file request.
Upvotes: 3