2

Is there anyway to get this done in plain Javascript?

When person click on the the following:

<div id=mydiv">Left click for download</div>

How would the Javascript look? I'm using:

$('#mydiv').click(function() {
  window.location.href('where_my_File_is.file');
});

But this just opens it. Anyone got a simple javascript script?

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • 2
    This depends both on how the server serves the file and how the browser handles this service; it's not something you can control on the client side with JavaScript – Explosion Pills Mar 05 '13 at 23:12
  • http://stackoverflow.com/questions/727144/browser-download-file-prompt-using-javascript or http://stackoverflow.com/questions/5192917/force-download-through-js-or-query – mccannf Mar 05 '13 at 23:29

1 Answers1

3

The answers linked in the comments explain why this can't be done in Javascript and instead that it needs to be done on the server-side. This one in particular explains why this is the case:

https://stackoverflow.com/a/5192922/560114

I just wanted to add that there is one way to initiate a download on the client-side, but it requires the use of Flash, and it probably wouldn't help you here because its purpose is to make it possible to download text files that you've generated using Javascript:

https://github.com/dcneiner/Downloadify

If it's a remote file, then the best way to force the download would be to have the server read it into memory and then output it with the headers necessary to force a download. Whether it's local or remote, at minimum the header from the server needs to include Content-Disposition: attachment. Here's a cross-browser example in PHP:

http://davidwalsh.name/php-force-download

Community
  • 1
  • 1
Matt Browne
  • 12,169
  • 4
  • 59
  • 75