我正在尝试让我的系统允许在单击超链接时下载文件。下面的代码显示有关要下载的文件的信息,此信息是从数据库中收集的。
代码显示在表中,单击超链接时应进行下载。变量" $ file"包含存储在数据库中的文件路径。单击此按钮时,应启动download.php文件,该文件应允许下载文件。但是,打开白页而没有任何反应。
YourPurchases.php
if (count($reports) != 0) {
foreach ($reports as $report) {
$title = $report['reportID'];
$rep_ID = $report['reportName'];
$reportSubCat = $report['subcategoryName'];
$uploadedBy = $report['userID'];
$numPages = $report['pageTotal'];
$file = $report['location']; // this is the file path stored in the database
$purchasedreportstable .= '<table>
<tr>
<th>Report ID  </th>
<th>Report Name   </th>
<th>Report SubCategory   </th>
<th>Uploaded By   </th>
<th>Page Total  </th>
<th>Download </th>
</tr>
<tr>
<td>'.$title.'</td>
<td>'.$rep_ID.'</td>
<td>'.$reportSubCat.'</td>
<td>'.$uploadedBy.'</td>
<td>'.$numPages.'</td>
<td> <a href="download.php file='.$file.'">Download</a>
</tr>';
}
$purchasedreportstable .= '</table>';
;
echo $purchasedreportstable;
的download.php
<?php
function downloadFile($file,$speed=1024){
if (file_exists($file)) {
if(is_dir($file)){return 'isdir';}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.sprintf("%u", filesize($file)));
ob_clean();
$handle = fopen($file, "rb");
$chunksize=(sprintf("%u", filesize($file))/$speed);
set_time_limit(0);
while (!feof($handle)) {
echo fgets($handle, $chunksize);
flush();
}
fclose($handle);
die;
}else{
return false;
}
return;
}
?>
数据库中的文件路径类似于 reports / upload1_60b7d515219902288b.pdf
非常感谢任何帮助,
由于
答案 0 :(得分:2)
根据您发布的内容判断,预计会出现空白屏幕,因为您的download.php
代码是一个永远称为的函数。
尝试把它放在底部:
downloadFile($_GET['file']);
如果返回false,您可能还需要检查返回值:
if(!downloadFile($_GET['file']))
echo 'Error encountered when trying to download file!';
答案 1 :(得分:1)
在download.php中,您需要先从URL获取文件名。您正在生成指向该页面的链接,但从不从URL中触发文件名或触发该功能。此代码低于函数的最后一个括号。
if (isset($_GET['file'])) {
$file = $_GET['file']
}
$result = downloadFile($file);
if ($result == FALSE) {
echo "Sorry, file does not exist.";
}