Is it possible to initiate a download prompt in the browser for recognized MIME types using only JavaScript (client-side approach)?
I would like to allow the user to directly download a file with a single click. There is however a problem when it comes to known MIME types like HTML, audio, video, etc. Ideally, I would like to trigger a download prompt for audio/video files. Ultimately, I would like to do it for HTML documents too. The main idea is to make it easy for users to download files without asking them to navigate into the context menu.
I think for example to people that are not really comfortable with a computer and its main functions. These people will surely prefer a better way than "save as".
The reason why I am looking for a JavaScript solution is that the PHP approach only works if you are in a web site context. Whenever you are inside a plugin or injected script context (i.e. developing a plugin for Firefox, Chrome or Safari), you may want to avoid asking for a server-side response.
I tried to achieve this with window.open()
and document.execCommand("saveAs",...
. It does work, although it is glitchy and fails for huge files.
Then, I tried Downloadify which does not work in every situations.
Is there a pure JavaScript, no Ajax way to trigger a download prompt so the user can directly download a file using a simple left click?
There is a new download
attribute in HTML5 that you can annote links with. It indicates to the browser that the resource should be downloaded rather than navigated to. Right now, it only works in Chrome, but it is part of the HTML spec and will hopefully be adopted by other browser soon.
Demo: http://html5-demos.appspot.com/static/a.download.html More info: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
If someone reaches this question now the best solution is
<a href="example" download target="_blank">
If the browser supports the HTML5 attribute download will start the download of the file, otherwise (in case of Internet Explorer and old browsers) the link will open another tab window with the file to download.
You can use <a href="example" download>
. This is HTML5 and it works with Chrome, Firefox and Edge (but not with Internet Explorer, not even modern versions).