有两种方法可以做到这一点 - 一种使用 JS,一种使用 PHP。
在这个网站的 JS 中:
<a href="javascript:void(0);"
onclick="document.execCommand('SaveAs',true,'file.html');"
>Save this page</a>
在 PHP 中创建一个名为的脚本download.php
,类似于以下代码:
<?php
// Force download of image file specified in URL query string and which
// is in the same directory as the download.php script.
if(empty($_GET['img'])) {
header("HTTP/1.0 404 Not Found");
return;
}
$basename = basename($_GET['img']);
$filename = __DIR__ . '/' . $basename; // don't accept other directories
$mime = ($mime = getimagesize($filename)) ? $mime['mime'] : $mime;
$size = filesize($filename);
$fp = fopen($filename, "rb");
if (!($mime && $size && $fp)) {
// Error.
return;
}
header("Content-type: " . $mime);
header("Content-Length: " . $size);
// NOTE: Possible header injection via $basename
header("Content-Disposition: attachment; filename=" . $basename);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
fpassthru($fp);
然后将图像链接设置为指向此文件,如下所示:
<img src="/images/download.php?img=imagename.jpg" alt="test">