jQuery 使用 JavaScript 下载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17311645/
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
Download image with JavaScript
提问by u283863
Right now I have a canvas
and I want to save it as PNG. I can do it with all those fancy complicated file system API, but I don't really like them.
现在我有一个canvas
,我想将它保存为 PNG。我可以用所有那些花哨的复杂文件系统 API 来做到这一点,但我真的不喜欢它们。
I know if there is a link with download
attribute on it:
我知道是否有一个带有download
属性的链接:
<a href="img.png" download="output.png">Download</a>
it will download the file if the user clicks on it. Therefore I came up with this:
如果用户点击它,它将下载文件。因此我想出了这个:
$("<a>")
.attr("href", "img.png")
.attr("download", "output.png")
.appendTo("body")
.click()
.remove();
Demo: http://jsfiddle.net/DerekL/Wx7wn/
演示:http: //jsfiddle.net/DerekL/Wx7wn/
However, it doesn't seem to work. Does it have to be trigger by an user action? Or else why didn't it work?
但是,它似乎不起作用。它是否必须由用户操作触发?否则为什么它不起作用?
回答by Ian
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
问题在于 jQuery 不会触发元素的本机click
事件,<a>
因此不会发生导航( 的正常行为<a>
),因此您需要手动执行此操作。对于几乎所有其他场景,本机 DOM 事件都会被触发(至少尝试过 - 它在 try/catch 中)。
To trigger it manually, try:
要手动触发它,请尝试:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO:http://jsfiddle.net/HTggQ/
演示:http : //jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
当前 jQuery 源中的相关行:https: //github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
回答by Oriol
As @Ian explained, the problem is that jQuery's click()
is not the same as the native one.
正如@Ian解释的那样,问题在于 jQueryclick()
与原生的不同。
Therefore, consider using vanilla-js instead of jQuery:
因此,请考虑使用 vanilla-js 而不是 jQuery:
var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);