强制浏览器下载带有Javascript窗口的图像。打开?

2022-08-30 16:00:46

有没有办法在单击图像后将其下载(无需右键单击将图像另存为)?

我正在使用一个小的Javascript函数来调用下载页面:

<a href="#" 
   onclick="window.open('download.php?file=test.jpg', 'download', 'status=0');"
>Click to download</a>

在下载.php页面中,我有这样的东西:

$file = $_GET['file'];
header('Content-Description: File Transfer');
header("Content-type: image/jpg");
header("Content-disposition: attachment; filename= ".$file."");
readfile($file);

但它不起作用。我做错了什么?
提前致谢!


答案 1

使用应用程序/八位字节流而不是图像/jpg

如果在应用程序/八位字节流内容类型的响应中使用 [Content-Disposition] 标头,则隐含的建议是用户代理不应显示响应,而应直接输入“将响应另存为...”。对话。
— RFC 2616 – 19.5.1 内容处置


答案 2

我想你忘了在标题上添加路径

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;
    }
}