PHP初学者。文件上传成功,但我的浏览器没有下载文件,而是读取文件。所以我参考了其他线程,发现下面的代码不起作用。我想在单击超级链接下载时下载文件。从MySQL数据库中选择了路径。
$rows = mysqli_num_rows($result);
if($rows>0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<div> <?php echo $row['Object_Name'];?>
<a href="<?php
$file_url = $row['Object_Path'];
header('Content-Type: application/octet-stream');
header("Content-disposition: attachment; filename='"".$row['Object_Name']. "'"");
readfile($file_url);
?>">Download</a><br>
</div>
<?php
}
}
在一个名为download.php的页面中,有以下代码:
<?php
$filename = 'file.pdf';//this should be the name of the file you want to download
header('Pragma: public');
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: application/pdf');
header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
?>
然后你的主页应该有一个下载页面的链接,如下所示:
<a href="download.php">DOWNLOAD</a>
如果这对你有用,请告诉我。
编辑:
我之前的例子是下载一个pdf文件。如果您想下载不同类型的文件,则必须稍微修改几行。我建议您先尝试下载一个带有以前代码的pdf文件,然后在其他文件上完成测试
要从数据库中检索路径,可以使用MySQL(PDO)。
$sqlStatement = "SELECT path FROM my_table WHERE some_id = ".$something;
/*if you are retrieving the path from the database,
you probably have a lot of different paths available
there, so only you know the criteria which will decide
which of the many paths it is that you choose to extract*/
$sqlPrepared = $connection->prepare($sqlStatement);
$sqlPrepared->execute();
$row_info = fetch($sqlPrepared);
$filename = $row_info['path'];// this would be the $filename = 'file.pdf'
//that was in the example above
如果你不确定如何连接到数据库,网上有很多文章解释MySQL相对简单。
我希望这有帮助:)
您必须使用两个独立的文件。
在链接页面中,您可以输出如下HTML:
<a href="http://www.example.com/download.php?file=1">Download file 1</a>
<a href="http://www.example.com/download.php?file=2">Download file 2</a>
<a href="http://www.example.com/download.php?file=3">Download file 3</a>
(...)
如果您愿意,可以使用<form>
。
然后,在download.php中:
使用GET/POST参数(上例中的
$_GET['file']
)选择合适的文件;发送适当的标头(如原始代码中的标头);
回显您的文件(您可以使用
readfile
);强制:此脚本中没有其他输出!即使是一个额外的空间也会损坏下载的文件。