Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force download with HTML/JavaScript?

I have a link and, if a user clicks it, I need 2 things to happen:

  • A proper HTTP response is sent to the user (especially with Content-Type: video/mp4)
  • and a video file will automatically begin downloading.

I have seen something of the sort with PHP, but is it possible only with HTML/JavaScript?

like image 295
Alex1987 Avatar asked Feb 19 '10 10:02

Alex1987


People also ask

How do I force a download in HTML?

You might point that to that file with a link. In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead.

How do I trigger a download when clicking HTML button or Javascript?

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute. The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded.

How do you make a file downloadable in Javascript?

To receive our files URL, we use URL. createObjectURL() which receives our file object as a parameter. Then, specify the name the saved file should have by default with setting the download attribute of the link. Finally, we mount the link in the DOM, click it artificially, and remove it from the DOM.


1 Answers

you can use the download attribute

<a href="http..." download></a>

or specify a filename using

<a href="http..." download="filename.pdf"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

like image 109
Bruce Aldridge Avatar answered Oct 02 '22 01:10

Bruce Aldridge