How can I force an Image download in the browser?

前端 未结 2 2150
长情又很酷
长情又很酷 2020-12-01 13:30

I want to force user to download images. Not open in browser.

It is possible to use HTML5 this attribute download but currently only Chrome sup

相关标签:
2条回答
  • 2020-12-01 13:51

    There's two ways to do this - one with JS, one with PHP.

    In JS from this site:

    <a href="javascript:void(0);"
     onclick="document.execCommand('SaveAs',true,'file.html');"
     >Save this page</a>
    

    In PHP create a script named download.php that is similar to the following code:

    <?php
    // Force download of image file specified in URL query string and which
    // is in the same directory as the download.php script.
    
    if(empty($_GET['img'])) {
       header("HTTP/1.0 404 Not Found");
       return;
    }
    
    $basename = basename($_GET['img']);
    $filename = __DIR__ . '/' . $basename; // don't accept other directories
    
    $mime = ($mime = getimagesize($filename)) ? $mime['mime'] : $mime;
    $size = filesize($filename);
    $fp   = fopen($filename, "rb");
    if (!($mime && $size && $fp)) {
      // Error.
      return;
    }
    
    header("Content-type: " . $mime);
    header("Content-Length: " . $size);
    // NOTE: Possible header injection via $basename
    header("Content-Disposition: attachment; filename=" . $basename);
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    fpassthru($fp);
    

    Then set the image link to point to this file like this:

    <img src="/images/download.php?img=imagename.jpg" alt="test">
    
    0 讨论(0)
  • 2020-12-01 13:56

    Try this in your .htaccess instead:

    <FilesMatch "\.(?i:jpg|gif|png)$">
      ForceType application/octet-stream
      Header set Content-Disposition attachment
    </FilesMatch>
    
    0 讨论(0)
提交回复
热议问题