admin管理员组

文章数量:1389762

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?

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?

Share Improve this question asked Dec 20, 2011 at 19:35 Abdul RaufAbdul Rauf 431 gold badge3 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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

You can force a download via a PHP (or other server-side language) script like this:

$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.

$('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.

Just use a hidden iframe that you set the source attribute on when you click the button.

HTML

<input class="download" href="http://site./imageHandler.ashx" value="Download"/>

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)

本文标签: javascriptdirectly Download Image by click on Download buttonStack Overflow