从PHP中的mySQL数据库下载文件

时间:2018-11-10 13:47:25

标签: php mysql download

我有3个文件:

config.php

<?php

$db = new PDO("mysql:host=localhost;dbname=datarepo", "root", "");

?>

data.php (显示我数据库中文件表的数据存储库)

<?php

<table class ="table">
<thead>

<tr>
<th>#</th>
<th>File</th>
<th>Action</th>
</tr>

</thead>

<tbody>
<?php
include('config.php');

$stmt = $db -> prepare("SELECT * FROM files");
$stmt->execute();


while($row = $stmt->fetch()){
?>

<tr>
 <td> <?php echo $row["id"]?></td>
 <td> <?php echo $row["name"]?></td>
 <td><a href="download.php?id=<?php echo $row["id"]?>" class="btn btn-primary">Download</a></td>
</tr>

<?php
}
?>

</tbody>

</table>

?>

download.php

<?php

include "config.php";
if(isset($_GET['id'])){

    $id = $_GET['id'];
    $stmt = $db -> prepare("select * from files where id=?");
    $stmt->bindParam(1,$id);
    $stmt->execute();
    $data = $stmt -> fetch();

    $file = 'dpo'.$data['name'];

    if(file_exists($file)){


        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Content-Type:'.$data['mime']);
        header ('Content-Length:'.filesize($file));
        readfile($file);
        exit;

    }

}
?>

当我尝试从the data repository (data.php下载文件时,我将被带到一个空白页面,但没有文件被下载,其网址为:http://localhost/dpo/download.php?id=1

这是mySQL中'files' table from the 'datarepo' database的示例。

我的问题是,如何获取要下载的文件?我知道不建议将文件上传到数据库,但是对于此项目,我必须这样做。

作为参考,这是我的 upload.php (请暂时忽略文件卫生):

<?php

include('config.php');

if(isset($_POST["submitfile"])) {

    $fileName = $_FILES['file']['name'];
    $fileSize = $_FILES['file']['size'];
    $fileError = $_FILES['file']['error'];
    $fileType = $_FILES['file']['type'];
    $data = file_get_contents($_FILES['file']['tmp_name']);

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('csv','doc','docx','jpg','pdf','png');


    if (in_array($fileActualExt, $allowed)){
        if ($fileError == 0){
            if ($fileSize < 5000000){
                $stmt = $db ->prepare("insert into files values('',?,?,?,?)");
                $stmt ->bindParam(1,$fileName);
                $stmt ->bindParam(2,$fileType);
                $stmt ->bindParam(3,$fileSize);
                $stmt ->bindParam(4,$data);
                $stmt ->execute();


                echo "File uploaded successfully.";

            }

            else {
                echo "File size is too big.";
            }
        } else {
            echo "There were was an error uploading the file.";
        }

    } else {
        echo "File format not supported.";

    }

}
?>

0 个答案:

没有答案