我在为网站的点击功能添加下载图像。我试图使用PHP来做到这一点,据我所知,没有办法在HTML中做到这一点,没有它链接到另一个空白页面,然后右键单击另存为,这不是我想要的。 我在这里发现了这段代码,并希望对其进行调整,但是我担心会破坏它,因为我对PHP的理解并不广泛。另外,我需要在多个文件上使用它,但是我使用的PHP建议您只能在一个文件中使用它,这意味着我可能需要大量的PHP文件,每个文件下载一个文件?点击下载图片 - 使用PHP
无论如何,我不确定,但如果有人能够帮助我,我可以帮助调整代码。 图片直接来自网站以下目录: /img/bkg/img1.jpg 这也跟在img2-5之后。
不管怎么说,这是在主文件中用于显示图像和链接到PHP文件下载代码:
<a href="download.php?file=path/<?=$row['img1.jpg']?>">
<img src="img/bkg/img1.jpg" alt="CWP - Wallpaper 1" width="1056" height="600"/>
</a>
这是我需要为这些文件和正确的目录调整的代码:
<?php
$file = $_GET['file'];
download_file($file);
function download_file($fullPath){
// Must be fresh start
if(headers_sent())
die('Headers Sent');
// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// File Exists?
if(file_exists($fullPath)){
// Parse Info/Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile($fullPath);
} else
die('File Not Found');
}
?>
对不起,如果上面是一个愚蠢的问题,但我宁愿寻求这种帮助不是遍地打破它。我不确定我在哪里替换文件和目录等等,我想说得对。
任何帮助,非常感谢。只要你喜欢
<a href="download.php?file=path/<?=$row['img1.jpg']?>">
页面:
文件名被传递到查询字符串,只是改变每个链接的文件名,它应该工作正常? – adeneo
你真的应该自己尝试这样做,或者至少了解脚本正在做什么:例如,没有输入验证,如果有人用'download.php?file = ../../../ etc/passwd'你可能会遇到很大的问题。 – jeroen
关于你的问题,你想单击下载多个文件,或只是在一个页面上下载多个文件? – jeroen