php - PHP从服务器下载文件打开文件而不是下载
问题描述
我一直在练习在 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
上面的代码在本地主机上运行良好,但在服务器上它不起作用,只要我单击下载按钮,它就会打开损坏的文件。谢谢
解决方案
将下载属性添加到链接
<a href="checkFile.php?docum_id=<?php echo $file['id'] ?>" download><?php echo $lang['download']?></a>
它会告诉浏览器加载而不是打开
推荐阅读
- jquery - 位置方法而不是 jquery 事件中的选择器
- python - AttributeError:“列表”对象没有属性“值”-用于 Azure DevOps 的 Python API
- sql - 如何在另一台服务器中获取存储过程的实际脚本?
- xml - 使用 XSL 转换合并两个 XML 文件
- node.js - 告诉 Typedoc 不要加载 Jasmine 注释
- javascript - Grave (`) 被标记为非法令牌
- elasticsearch - 如何在elasticsearch中保存地理数据
- excel - InputBox 数据验证和结束循环
- tinybutstrong - 使用 TBS 准备好的报表
- jestjs - 如何开玩笑地将测试中的数据传递给记者?