javascript 点击下载按钮直接下载图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8580924/
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
directly Download Image by click on Download button
提问by Abdul Rauf
i want to create wallpapers page for my website. and i want people can download by clicking on download button directly rather than image view in browser and user right click on that and then save as image. is there any solution with java script?
我想为我的网站创建壁纸页面。我希望人们可以通过直接单击下载按钮而不是浏览器中的图像视图来下载,然后用户右键单击该按钮然后另存为图像。java脚本有什么解决方案吗?
回答by Derp A. Round
You need to force the content type of the image being sent by the server. There isn't a way to do this client-side.
您需要强制服务器发送的图像的内容类型。没有办法在客户端执行此操作。
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=myimage.png
回答by Jasper
You can force a download via a PHP (or other server-side language) script like this:
您可以通过 PHP(或其他服务器端语言)脚本强制下载,如下所示:
$file = $_GET['file'];
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");//notice this content-type, it will force a download since browsers think that's what they should do with .exe files
header("Content-disposition: attachment; filename= ".$file."");
readfile($file);
Then in your JavaScript code you can direct users to this script with the GET variable file
being populated by the JavaScript.
然后在您的 JavaScript 代码中,您可以使用file
JavaScript 填充的 GET 变量将用户定向到此脚本。
$('a.download_link').on('click', function (event) {
event.preventDefault();//prevent the normal click action from occuring
window.location = '/path/to/server-side.php?file=' + encodeURIComponent(this.href);
});
This will add a click
event handler to any links that have the .download_link
class to direct the browser to the PHP script above to force a download.
这将向click
任何具有.download_link
将浏览器定向到上述 PHP 脚本以强制下载的类的链接添加一个事件处理程序。
回答by SliverNinja - MSFT
Just use a hidden iframe that you set the source attribute on when you click the button.
只需使用在单击按钮时设置源属性的隐藏 iframe。
HTML
HTML
<input class="download" href="http://site.com/imageHandler.ashx" value="Download"/>
Javascript
Javascript
$("input.download").click(function() { $("iframeID").attr("src", $(this).attr("href")); });
You also need to set the content-type using the custom image handler (whichever server-side language you are using)
您还需要使用自定义图像处理程序(无论您使用哪种服务器端语言)设置内容类型