强制将远程托管图像下载到浏览器

时间:2014-10-27 13:47:43

标签: javascript php jquery image download

假设我有一个托管Google的图片:https://www.google.ae/images/srpr/logo11w.png

我想下载此图片文件,而不是直接在浏览器中打开。

我试过了:

<?php
function downloadFile($file, $type)
{
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: $type");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
readfile($file);
}
downloadFile("img.jpg", "image/jpg");
?>

这适用于本地托管的图片,而不适用于像上面的Google示例一样远程托管的图片。

1 个答案:

答案 0 :(得分:3)

readfile() manual page上的第一个示例名为&#39;使用readfile()&#39;强制下载,并带有.gif文件:

$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

Notes 部分下面是以下提示:

  

如果已启用fopen包装,则可以使用此函数将URL用作文件名。有关如何指定文件名的更多详细信息,请参阅fopen()。有关各种包装器具有哪些功能的信息,使用说明以及它们可能提供的任何预定义变量的信息,请参阅支持的协议和包装器。

因此,如果您只是将$file = 'https://www.google.ae/images/srpr/logo11w.png';替换为$file = 'monkey.gif';,则上述脚本应强制下载图片。

当然,这种方法的一大缺点是图像首先传输到您的服务器,然后下载到客户端。但是,正如@charlietfl wrote&#39;您无法控制其他服务器处理请求的方式。&#39;因此,您无法直接链接到原始来源并希望下载该文件。

相关问题