php - 用mysql下载文件

时间:2017-08-13 13:33:40

标签: php mysql

我创建的网站应该能够让用户上传和下载文件。上载文件时,名称和路径存储在数据库中。要下载文件,我创建了一个download.php,其中应列出上传的文件。我遇到的问题是下载页面不起作用,没有显示文件,并且表明路径不会被定义。

index.php文件:

<?php
include('db.php');    
$sql  = "SELECT * FROM documents";
$res = mysqli_query($con, $sql);    
?>

<html>
    <head>
        <title>Documents</title>
    </head>
<body>
    <nav id="nav">
        <ul>
            <li><a href="upload.php">Upload</a></li>
            <li><a href="download.php">Download</a></li>
        </ul>
    </nav>

        <?php            
        while ($row = mysqli_fetch_array($res)) {

            $name = $row ['name'];
            $path = $row ['path'];                               
        }      
        ?>
</body>
</html>

upload.php文件:

<?php
include("db.php");

if(isset($_POST['submit'])){

    $name = $_FILES['myfile']['name'];
    $tmp_name = $_FILES['myfile']['tmp_name'];

    if($name){

        $location = "/storage/ssd1/139/2476139/uploads/$name";
        move_uploaded_file($tmp_name, $location);
        $query = mysqli_query($con, "INSERT INTO documents (name, path) VALUES('$name', '$location')");
        header('Location: index.php');
    }
    else 
        die("Please select a file.");    
}
?>

<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label>Browse File:</label>

        <input type="file" name="myfile">
        <input type="submit" name="submit" value="Upload" onclick="index.php">
    </form>

</body>    
</html>

download.php文件:

<?php    
include('db.php');

echo $name."<a href='download.php?dow=$path'>Download</a><br>";

if(isset($_GET['dow'])) {
    $path = $_GET['dow'];
    $res = mysqli_query($con, "SELECT * FROM documents WHERE path='$path'");

    readfile($path);   
}
?>

1 个答案:

答案 0 :(得分:0)

您不能将打印下载链接的回显线放入用于下载文件的脚本中。用户将如何首先访问此页面?

相反,请将您的下载链接放在主页中,您已经打印过这样的文档:

<?php            
while ($row = mysqli_fetch_array($res)) {
    $name = $row ['name'];
    $path = $row ['path'];

    echo '<a href="download.php?dow='.$path.'">'.$name.'</a>';                           
}
?>

然后你的download.php脚本将通过$_GET['dow'];变量获取路径,你可以在download.php脚本中使用它,就像你已经做的那样。