Javascript 点击下载按钮直接下载图片

Javascript 点击下载按钮直接下载图片,javascript,jquery,ajax,Javascript,Jquery,Ajax,我想为我的网站创建壁纸页面。我希望人们可以直接点击下载按钮来下载,而不是在浏览器中查看图像,然后用户右键点击该按钮,然后另存为图像。java脚本有什么解决方案吗?您需要强制服务器发送的图像的内容类型。没有一种方法可以在客户端执行此操作 Content-Type: application/octet-stream Content-Disposition: attachment;filename=myimage.png 您可以通过PHP(或其他服务器端语言)脚本强制下载,如下所示: $file =

我想为我的网站创建壁纸页面。我希望人们可以直接点击下载按钮来下载,而不是在浏览器中查看图像,然后用户右键点击该按钮,然后另存为图像。java脚本有什么解决方案吗?

您需要强制服务器发送的图像的内容类型。没有一种方法可以在客户端执行此操作

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=myimage.png

您可以通过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);
然后,在JavaScript代码中,您可以使用由JavaScript填充的GET变量
file
将用户引导到此脚本

$('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);
});

这将向包含
的任何链接添加
单击
事件处理程序。download\u link
类可将浏览器指向上面的PHP脚本以强制下载。

只需使用一个隐藏的iframe,当您单击该按钮时,您可以设置源属性

HTML
您还需要使用自定义图像处理程序(无论您使用哪种服务器端语言)设置内容类型javascript@AbdulRauf:如果您找到了一个这样做的站点,为什么不查看源代码并使用相同的技术?@AbdulRauf您可以向服务器端文件发出AJAX请求,强制执行这些标题。。。但强制下载图像的不是客户端代码本身,我有html页面,因此我想使用这个选项。因此,有了这段代码,我只需要用这个Http链接替换图像链接的链接?您不能使用图像的静态链接。您需要一个活动脚本页面来分配内容类型(jsp、aspx、asp、php等)。
<input class="download" href="http://site.com/imageHandler.ashx" value="Download"/>
$("input.download").click(function() { $("iframeID").attr("src", $(this).attr("href")); });