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

标签 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 示例那样远程托管的图像。

最佳答案

readfile() manual page 上的第一个例子标题为“使用 readfile() 强制下载”,带有 .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 部分下有以下提示:

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

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

当然,这种方法的最大缺点是图像会先传输到您的服务器,然后再下载到客户端。但是,作为 @charlietfl wrote “你无法控制另一台服务器如何处理请求。”所以您不能直接链接到原始来源并期望下载文件。

关于javascript - 强制将远程托管的图像下载到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589020/

相关文章:

javascript - TinyMCE 和 fancybox 交互错误

javascript - 使用 JavaScript 将上标应用于所选内容

javascript - 使用 Range.insertNode() 动态添加图像到 DOM

php - 如何在 UTF-8 MySQL 中存储 £ 符号

javascript - 为什么我的 jQuery .ready() 函数不起作用?

jquery - 使用 jQuery 提交表单更改样式

javascript - 从 js 添加媒体查询

php - 从 webroot 访问 cakephp session 变量

Java 客户端 POST 到 php 脚本 - 空 $_POST

jquery - 限制 html5 Canvas 内的移动?