简体   繁体   中英

How to add download button to external image on our site

I have a external url image attached with tags in my page. So i tried all methods to add download button to image.

I have added download attribute but instead of downloading file the button taken me to image file url in new windows or same window.

So please tell me best way to add download button which will give facility of download on one click.

Any Php or js code that worked for you ?

Note/Edit :- Suppose It Is My Page ( http://manvik2.sg-host.com/m.php ) So If This Generate Tool One Image Every Time. So I Want To Add Download Button Which Work On All Images

You should try to add a link tag around your image in the HTML :

<a href="link/to/image.jpg" download="name-of-image">
    <img src="link/to/image.jpg" alt="your-image" />
</a>

Hi there you can't do it with pure html download attributes.

I don't see clearly how can we do it with js.

For a php solution you will need to curl url of your image and put the image in your server with the same domain name, then you can use the download attributes and it will work

EDIT: For the php edition i can be that : you need to create a files/ folder first

<?php
function grab_image($url,$saveto){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // <-- don't forget this
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // <-- and this
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

$link = "https://images-na.ssl-images-amazon.com/images/I/81tISKde7HL._AC_SL1500_.jpg"; // your link 
$temp_match;
preg_match('/(?=\w+\.\w{3,4}$).+/',$link,$temp_match); // get the filename from url return an array

$file_name = $temp_match[0]; //get the name from the array

$path= ('./files/'.$file_name); // create path 
grab_image($link,$path);


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <a href="<?= $path ?>" download="<?=$file_name?>">download</a>    
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM