我一直在练习在Mysql中保存文件名,并使用GET
方法从服务器下载文件。上载效果很好,但是从文件夹下载文件时,文件会自动打开,不会下载。
这是我的代码,用于从文件夹
<?php
include 'includes/ann.php';
// connect to the database
$username = "uname";
$password = "pass";
$database = "practice5";
$servername = "localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM documents";
$result = mysqli_query($conn, $sql);
$myfile = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Downloads files
if (isset($_GET['docum_id'])) {
$ids = $_GET['docum_id'];
// fetch file to download from database
$sql = "SELECT * FROM documents WHERE id=$ids";
$result = mysqli_query($conn, $sql);
$file = mysqli_fetch_assoc($result);
$filepath = 'docs/' . $file['name'];
if (file_exists($filepath)) {
ob_start();
header('Content-Description: File Transfer');
header('Content-Type: application/octetstream');
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate,post-check=0, pre-check=0');
header('Content-Type: application/force-download');
header('Pragma: public');
header('Content-Length: ' . filesize('docs/' . $file['name']));
ob_clean();
flush();
readfile('docs/' . $file['name']);
exit();
}
else
{
echo "No files found";
}
}
?>
<div style="margin-top: 100px;" class="container">
<div class="row">
<div class="col-lg-8 mx-auto">
<h2 style="text-align: center">Download</h2>
<table id="example" class="table table-bordered">
<thead>
<tr class="bg-warning">
<th><?php echo $lang['tableheadOne']?></th>
<th><?php echo $lang['murtiletit']?></th>
<th><?php echo $lang['murtiledesc']?></th>
</tr>
</thead>
<tbody>
<?php foreach ($myfile as $file): ?>
<tr>
<td><?php echo $file['id']; ?></td>
<td><?php echo $file['title']; ?></td>
<td><?php echo $file['description']; ?>
<a href="checkFile.php?docum_id=<?php echo $file['id'] ?>"><?php echo $lang['download']?></a></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
</div
..footer
上面的代码在localhost上运行良好,但在服务器上却无法正常运行,只要单击下载按钮,它就会打开损坏的文件。谢谢
答案 0 :(得分:0)
将下载属性添加到链接
<a href="checkFile.php?docum_id=<?php echo $file['id'] ?>" download><?php echo $lang['download']?></a>
它将告诉浏览器加载而不是打开