强制浏览器使用 Javascript window.open 下载图像?

IT技术 php javascript
2021-02-16 19:29:26

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

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

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

在 download.php 页面中,我有类似的内容:

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

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

6个回答

使用application/octet-stream而不是image/jpg

如果在具有 application/octet-stream content-type 的响应中使用 [the Content-Disposition] 标头,则暗示的建议是用户代理不应显示响应,而是直接输入“将响应另存为...”对话。
RFC 2616 – 19.5.1 内容处置

@Jay Wit:除了使用readfile或缓冲它外,不要做任何输出,以免它被发送到客户端。
2021-04-21 19:29:26
@秋葵; 某些文件名/目录包含空格是的,但这是一个问题吗?
2021-04-23 19:29:26
@Jay Wit:它readfile打印文件的内容。只需使用十六进制编辑器即可查看已发送的实际数据。
2021-04-26 19:29:26
保存为jpg,文件名正确。但是当我打开文件时它已损坏?所以看起来它实际上不是 jpeg
2021-05-03 19:29:26
@Jay Wit:您发送的数据可能不仅仅是文件的内容(例如一些空格等)。
2021-05-11 19:29:26

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

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

或者您可以将 .htaccess 文件用于所有图像文件。如果您想强制浏览器下载所有图像(来自表格列表):

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] 

这会查找图像文件并尝试强制将它们下载到浏览器中。-f RewriteConds 还检查文件是否存在。最后一条规则确保下载仅用于某些文件类型。

谢谢:-) 我也最喜欢它 ;-) 它很干净,没有使用 PHP 作为流.. 仅用于选定的目录。唉,它并不适合所有用例..
2021-04-25 19:29:26
为了让它在 IE 9 中适用于 JPG,我还必须添加Header set Content-Disposition attachment到 Apache 配置中。
2021-05-11 19:29:26

这对我有用

header("Pragma: public");
header('Content-disposition: attachment; filename='.$title);
header("Content-type: ".mime_content_type($sample_file));
header('Content-Transfer-Encoding: binary');
ob_clean(); 
flush(); 
readfile($sample_file);

我还将以下内容添加到 .htaccess

SetEnvIf Request_URI "\.jpg$" requested_jpg=jpg
Header add Content-Disposition "attachment" env=requested_jpg

不确定这是否有帮助?

如果您在 apache 服务器上,这非常简单。

  1. 在您的文件所在的目录中创建一个名为 .htaccess 的文件。对我来说是assets/.htaccess
  2. 将以下内容添加到文件中AddType application/octet-stream .jpg您可以为您需要的每个文件扩展名添加一个新行。例如AddType application/octet-stream .pdf
  3. 保存您的文件
  4. 清除浏览器缓存
  5. 刷新您的浏览器并享受!