使用javascript为用户提供图像下载 [英] Providing user a image download with javascript

查看:93
本文介绍了使用javascript为用户提供图像下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在网络上有一些网址图片。让我们说...
url是 http://hd.wallpaperswide.com /thumbs/abstract_crystal_structure-t2.jpg

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.

我试过这个..

window.location.href = Link;

但有时它只是在浏览器上打开图像..
有时下载提供为这是预期的。

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

如何实现..

推荐答案

假设有HTML5 / ES5浏览器,您可以使用 download 属性< a> 元素。

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


  1. 设置下载 < a> 上的属性为您想要的文件名。

  2. href 设置为图像的位置。

  3. 模拟点击它。

  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.

如果你已经使用< a> 作为下载按钮,您不必模拟点击,只需使用该元素。

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

请参阅我的回答 此处 了解更多信息,请记住您不需要做任何dataURI的东西因为你有直接链接。

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

这篇关于使用javascript为用户提供图像下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆