【问题标题】:How to add download button to external image on our site如何将下载按钮添加到我们网站上的外部图像
【发布时间】:2020-08-25 21:52:11
【问题描述】:

我的页面中有一个带有标签的外部 url 图片。所以我尝试了所有方法将下载按钮添加到图像。

我添加了下载属性,但不是下载文件,而是按钮将我带到新窗口或同一窗口中的图像文件网址。

所以请告诉我添加下载按钮的最佳方法,这将提供一键下载的便利。

任何适合您的 Php 或 js 代码?

注意/编辑:- 假设它是我的页面 (http://manvik2.sg-host.com/m.php) 所以如果这个工具每次生成一个图像。所以我想添加适用于所有图像的下载按钮

【问题讨论】:

    标签: javascript php html image download


    【解决方案1】:

    您应该尝试在 HTML 中的图像周围添加一个链接标签:

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

    【讨论】:

    • 那么我们如何添加按钮类型的链接呢?因为它没有任何文字。
    • 下载 也不能以这种方式工作。仅在新标签/同一标签中打开链接
    • 请注意,这是我附加到我的页面的外部图像。所以网址就像 - example.com/image.jpg
    • 您可以将外部链接放入您的 href 属性中。
    • 我知道!不说了,关注下载问题
    【解决方案2】:

    您好,您不能使用纯 html 下载属性来做到这一点。

    我看不清楚我们如何用js做到这一点。

    对于php解决方案,您需要卷曲您的图像的url并将图像以相同的域名放在您的服务器中,然后您可以使用下载属性并且它会起作用

    编辑: 对于 php 版本,我可以是: 您需要先创建一个files/ 文件夹

    <?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>
    

    【讨论】:

    • 我之前告诉过下载属性不起作用先生。 #我添加了下载属性,但不是下载文件,而是按钮将我带到新窗口或同一窗口中的图像文件网址。
    • 请详细说明 PHP 解决方案,因为这是我们最后的希望。
    • 如果 CURLOPT_WRITEFUNCTION 被实施以将内容提供给用户而不是先将其写入文件,那将是一个更好的用户体验。还禁用 CURLOPT_SSL_VERIFYPEER 另一个是安全风险
    • 这对 ssl 来说是正确的,它是从我拥有的 uni 代码中快速复制过去的。第一次看到CURLOPT_WRITEFUNCTION,我去看看,谢谢建议
    • @ThéaD 您的解决方案可以处理大量外部图像。 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多