如何通过 JavaScript 保存图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12238545/
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
How to save an image via JavaScript
提问by Nav
I want to download a image file (jpeg image) to the user files system when user selects a photo and clicks a button. So far I searched and found this linkand also this
当用户选择照片并单击按钮时,我想将图像文件(jpeg 图像)下载到用户文件系统。到目前为止,我搜索并找到了这个链接,还有这个
I saw in one blog that downloadify when used with jszip can enable this feature but it didn't specify any farther on this. Does any one know how to download the images. I have the links to the images and i just want the user to download it on his system rather than again query the server.
我在一个博客中看到 downloadify 与 jszip 一起使用时可以启用此功能,但它没有进一步说明。有谁知道怎么下载图片。我有图像的链接,我只希望用户将其下载到他的系统上,而不是再次查询服务器。
Can anyone provide me with an example please.
谁能给我提供一个例子。
采纳答案by Nav
Finally I did it. For anyone who may need this in the future here is how I did it using jquery
最后我做到了。对于将来可能需要此功能的任何人,这里是我使用 jquery 的方法
jQuery.ajax({
url: 'http://localhost:8080/yourwebsite/servlet?img=' + document.getElementById(id).alt,
//data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
// success: function() { alert("Success"); },
// error: function() { alert('Failed!'); },
// beforeSend: setHeader
});
this I had to do come across the problem of cross domain http requests which are usually blocked by most websites unless you follow some lengthy process. So, I made it simpler and called a get method in my servlet and passed it the url of the image from which it downloaded the image.This is much easier to do and even easier then this if you are on the same domain but that didn't meet my requirements and this code worked for me :)
我不得不遇到跨域 http 请求的问题,除非您遵循一些冗长的过程,否则这些请求通常会被大多数网站阻止。所以,我让它更简单,并在我的 servlet 中调用了一个 get 方法,并将它下载图像的图像的 url 传递给它。如果你在同一个域中,这更容易做到,甚至更容易不符合我的要求,此代码对我有用:)
回答by Andreas K?berle
You can load the image in an canvas element get the data url of the canvas and open a new window with the data url as source. Take a look at this example: https://gist.github.com/1875132
您可以在画布元素中加载图像,获取画布的数据 url,并以数据 url 作为源打开一个新窗口。看看这个例子:https: //gist.github.com/1875132
回答by Andrii Verbytskyi
Use the HTML5 download
attribute.
使用 HTML5download
属性。
As a choice you can set filenameas an attribute value.
作为一种选择,您可以将文件名设置为属性值。
<a href="/images/image-name.jpg" download="new-image-name.jpg">