5

I have to download a file (pdf/zip/txt ...) using jquery.

What i tried ??

<a href="abc.pdf">click</a>

When i click the link the file is opened in browser.

using jquery...

$('a').click(function(e)
{
e.preventDefault();
var link = $(this).attr('href');
window.location = link;
});

This also leads to open the file in browser. But i want to download it not display in browser.

In PHP we can use header('Content-Disposition: attachment; filename="test.mp3"');

But i have to use only jquery/javascript..

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97

1 Answers1

13

You can trigger a download by using the new HTML5 download attribute.

<a href="path_to_file" download="proposed_file_name">Download</a>

path_to_file is either an absolute or relative path, proposed_file_name the filename to save to (can be blank, then defaults to the actual filename).

jontewks
  • 458
  • 3
  • 7
  • Good to know! Also see no safari support. – jontewks Jul 02 '14 at 05:28
  • Yes this works in Chrome and Firefox unless the file/image is sourced on a different server: Chrome 65+ and Firefox only support same-origin download links. For example I use Amazon s3 for image storage making this solution not workable. – Mark Aug 25 '20 at 14:27
  • While this is a useful answer, it does not answer the question, which was how to download a file using jquery. – BobbyMick Nov 16 '21 at 13:30