javascript 强制浏览器使用 jquery 单击链接下载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19655465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force browser to download an image on click of a link using jquery
提问by Maninder
I would like to start download of an image on click of a link.
我想通过单击链接开始下载图像。
<a id="downloadImage" href="imagepath">Click here to download</a>
I know we can use download attribute of HTML5 (Force a browser to save file as after clicking link) but I would not like to use it as it will not be working in older versions of browsers. I did tried the method here: Download File Using Javascript/jQuerybut it opens the image in the iframe .
我知道我们可以使用 HTML5 的下载属性(点击链接后强制浏览器保存文件)但我不想使用它,因为它不能在旧版本的浏览器中工作。我确实尝试过这里的方法: 使用 Javascript/jQuery 下载文件但它在 iframe 中打开图像。
Can anybody help me to force a browser to download an image onclick of a link using jquery?
任何人都可以帮助我强制浏览器使用 jquery 单击链接下载图像吗?
回答by Vadim
As far as I know there is no client-side cross-browser solution for this issue (doesn't matter using jQuery or any other UI toolkit). What you need to do in order to trigger browser to download a file is to add some HTTP headers to the server response:
据我所知,此问题没有客户端跨浏览器解决方案(使用 jQuery 或任何其他 UI 工具包无关紧要)。为了触发浏览器下载文件,您需要做的是在服务器响应中添加一些 HTTP 标头:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename=image.jpg
Thispost may also be helpful for you.
这篇文章也可能对你有帮助。
回答by Vin Lim
You can use the downloadattribute, while not fully supported across browsers, you can use modernizrto support/fallback for unsupported browsers.
您可以使用下载属性,虽然浏览器不完全支持,但您可以使用 Modernizr来支持/回退不受支持的浏览器。
For supported browsers, check http://caniuse.com/#feat=download
对于支持的浏览器,请查看http://caniuse.com/#feat=download
<a href="/path/to/image.jpg" title="ImageName" download="ImageName" >
<img src="/path/to/image.jpg" alt="ImageName">
</a>