我找到了解释如何从PHP中的SQL数据库下载文件(在我的例子中是MP3)的帖子。很明显,为了启用下载,文件的$ path是必需的。我已将MP3上传到我的数据库,但没有上传路径,因为我不知道它会是什么。我习惯于通过关联数组访问我的对象,例如:$ row ['wholeMP3'];该项目作为longblob存储在数据库中。我不明白我的$ path对于这个项目是什么。如果有人可以请进一步向我解释,将不胜感激。
<?php
query2 = "SELECT* FROM MP3s_for_Sale WHERE id = :itemNum";
$LastProduct = $db->prepare($query2);
$LastProduct->bindvalue(':itemNum', $itemNum);
$LastProduct->execute();
//Need to figure out how to download
$rows = $LastProduct->fetchAll();
$LastProduct->closeCursor();
foreach ($rows as $row){
// I have created a column for the filename and extension called path
$filename = $row['path'];
$filesize = $row['filesize'];
//$size = filesize($yourfile);
//echo "size ".$size;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename='$filename'");
header("Content-Length: $filesize");
//what is $yourfile?
//readfile($yourfile);
//I put this here and it does transfer a file just not operable
echo $row['wholeMP3'];
}
?>
这是使用我在stackoverflow上找到的示例的更新。我现在有 我的表中的大小,路径/名称,类型和内容的列。我填写了必填字段,但仍然无效。它开始下载然后停止。这是我的新代码:
$query2 = "SELECT* FROM MP3s_for_Sale WHERE id = :itemNum";
$LastProduct = $db->prepare($query2);
$LastProduct->bindvalue(':itemNum', $itemNum);
$LastProduct->execute();
//Need to figure out how to download
$rows = $LastProduct->fetchAll();
$LastProduct->closeCursor();
foreach ($rows as $row){
$filename = $row['path'];
$filesize = $row['filesize'];
$content = $row['wholeMP3'];
$type = $row['type'];
header("Content-length: $filesize");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$filename");
ob_clean();
flush();
echo $content;
}
exit;