user1711245
user1711245

Reputation:

Providing user a image download with javascript

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..

Upvotes: 0

Views: 845

Answers (4)

Paul S.
Paul S.

Reputation: 66304

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.

Upvotes: 1

Cecchi
Cecchi

Reputation: 1535

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.

Upvotes: 0

jthomas
jthomas

Reputation: 858

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

https://github.com/dcneiner/Downloadify

Upvotes: 0

Brad
Brad

Reputation: 163272

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.)

Upvotes: 1

Related Questions