Force Browser to download Image with Javascript window.open?

前端 未结 11 816
感动是毒
感动是毒 2020-11-27 19:37

Is there a way to make an image a download once you click on it (without right-click save image as)?

I\'m using a small Javascript function to call the do

相关标签:
11条回答
  • 2020-11-27 20:03

    I think you forgot to add Path on the header

    if(isset($_GET['file'])){
        //Please give the Path like this
        $file = 'images/'.$_GET['file'];
    
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 20:04

    Use application/octet-stream instead of image/jpg:

    If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
    — RFC 2616 – 19.5.1 Content-Disposition

    0 讨论(0)
  • 2020-11-27 20:12

    Here's a way to force all files in a certain directory to be prompted for a download.

    Requirement

    1. Apache
    2. mod_headers enabled

    In your .htaccess or Apache configuration put the following.

    <Directory /path/to/downloadable/files>
        Header set Content-Disposition attachment
        Header set Content-Type application/octet-stream
    </Directory>
    
    0 讨论(0)
  • 2020-11-27 20:14

    Or you can use .htaccess file for all your image files. In case you want to force the browser to download all your images (f.e. from a table list):

    RewriteEngine On
    RewriteBase /
    RewriteCond %{QUERY_STRING} ^download$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .(jpe?g|gif|png)$ index.php?file=noFoundFilePage [L,NC]
    RewriteCond %{QUERY_STRING} ^download$
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .(jpe?g|gif|png)$ - [L,NC,T=application/octet-stream] 
    

    This looks for image files a tries to force download them into the browser. The -f RewriteConds also checks that the file exsist.. The last rule ensures that download is used only for certain file types.

    0 讨论(0)
  • 2020-11-27 20:14

    Once you’ve added the Content-Disposition: attachment header, you should be able to use a normal link:

    <a href="download.php?file=test.jpg">Click to download</a>
    

    What browsers have you tried this with?

    0 讨论(0)
提交回复
热议问题