0

lets say i have some url to a image on the web. lets say... url is "http://hd.wallpaperswide.com/thumbs/abstract_crystal_structure-t2.jpg"

Now I want when a user press a download button, he the image will be downloaded.

I've tried this..

window.location.href = Link;

But sometimes it just opens the image on the browser.. sometimes download is provided as it's expected.

How to achieve..

4 Answers4

1

The only way to do this is with the Content-Disposition header, server-side.

Content-Disposition: attachment; filename="somefile.jpg"

You cannot force this behavior with JavaScript. (You also cannot 100% rely on having this control, even with the Content-Disposition header. Support varies from browser to browser.)

Brad
  • 159,648
  • 54
  • 349
  • 530
1

Assuming a HTML5/ES5 browser, you can make use of the download attribute of the <a> element.

  1. Set the download attribute on an <a> to your desired filename.
  2. Set the href to the location of the image.
  3. Simulate a click on it.

If you're already using an <a> as your download button, you don't have to simulate the click, just use that element.

Please see my answer here for more, remember you don't need to do any dataURI stuff as you have a direct link.

Community
  • 1
  • 1
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

If you're willing to rely on Flash, this library could solve the problem.

https://github.com/dcneiner/Downloadify

jthomas
  • 858
  • 6
  • 19
0

You could, if you're willing to sacrifice the speed of the download, create a server-side script that acts as a proxy: it would download the file to your server and then pass it along to the client's browser with the appropriate headers (Content-Disposition: attachment) as mentioned in Brad's answer. Instead of linking to the file itself you would instead link to the "gateway" on your own server. The exact implementation will depend on your infrastructure and the language/libraries you choose to use.

There are numerous arguments against this approach (liability-wise, security-wise, and performance-wise) and I would not recommend it unless you have no alternatives.

Cecchi
  • 1,525
  • 9
  • 9