php中的文件类型和大小无法正确显示

时间:2017-12-19 10:30:45

标签: php html

所以,问题出在我的php页面中,除了文件类型和文件大小外,一切似乎都很完美。

我已经发布了预期结果和实际结果,如您所见。问题似乎是没有正确捕捉类型和大小,我发现我的代码没有任何问题..

感谢您的帮助!

HTML:

<!DOCTYPE html>
<html lang="sv">
    <head>
        <title>2.2.2 Uppladdning av fil</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form method="post" enctype="multipart/form-data" action="default.php">
            <p>
                <input type="file" name="file"/>
            </p>
            <p>
                <input type="submit" value="Sänd fil" name="push_button"/>
            </p>
        </form>
    </body>
</html>


<?php

    if(($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png")){

        move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
        $bild = $_FILES["file"]["name"];
        $bilden = $bild;
        echo'<img src="'.$bilden.'">';

    }else if ($_FILES["file"]["type"] == "text/plain"){
        $txt = "./uploads/" . $_FILES["file"]["name"];
        $open = fopen($txt, "r");
        fclose($openFile);

        echo fread($open, filesize($txt));

        header("Content-Type: text/plain");


    }else {
        header('Content-type: text/plain');
        echo "Name: " . $_FILES["file"]["name"];
        echo "\nType: " . $_FILES["file"]["type"];
        echo "\nSize: " . $_FILES["file"]["size"] . " Kb";
    }

?>

PHP:

预期结果:

Name: fireworks.mp3
Type: audio/mp3
Size: 7881.6875 Kb

实际结果:

Name: fireworks.mp3
Type: 
Size: 0 Kb

2 个答案:

答案 0 :(得分:0)

我认为你的一个问题是else部分的text / plain标题。这阻止我正确运行此表单。 如果我删除它,使用以下代码,一切都很好:

<!DOCTYPE html>
<html lang="sv">
<head>
    <title>2.2.2 Uppladdning av fil</title>
    <meta charset="UTF-8">
</head>
<body>
<form method="post" enctype="multipart/form-data" action="">
    <p>
        <input type="file" name="file"/>
    </p>
    <p>
        <input type="submit" value="Sänd fil" name="push_button"/>
    </p>
</form>
</body>
</html>

<?php

if(($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png")) {

    move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    $bild = $_FILES["file"]["name"];
    $bilden = $bild;
    echo'<img src="'.$bilden.'">';

} elseif ($_FILES["file"]["type"] == "text/plain") {
    $txt = "./uploads/" . $_FILES["file"]["name"];
    $open = fopen($txt, "r");
    fclose($openFile);

    echo fread($open, filesize($txt));

    header("Content-Type: text/plain");

} else {
    echo "Name: " . $_FILES["file"]["name"];
    echo "\nType: " . $_FILES["file"]["type"];
    echo "\nSize: " . $_FILES["file"]["size"] . " Kb";
}

结果我得到了一个PDF文件: 名称:invoice-124927.pdf类型:application / pdf文件大小:23609 Kb

答案 1 :(得分:-1)

您的内容类型错误

header('Content-type: text/plain');

尝试使用此音频

"Content-Type: audio/mpeg"