以相同的形式上传两个不同的文件

时间:2016-10-04 16:00:05

标签: php html5

这里的问题是,当我上传视频时,它运行得很完美,但不是图像让我很难弄清楚错误是什么

这就是HTML的样子:

<form action="index.php" method="post" enctype="multipart/form-data" >
   <h1>Browse for file to upload:</h1>
</div>
<div>
    <label for="file"><h1><b>Select Video</b></h1></label>
    <input type="file" name="fileToUpload1[]" id="fileToUpload" >

    <br><br>

    <label for="file"><h2><b>Select Image</b></h2></label>
    <input type="file" name="fileToUpload1[]" id="fileToUpload" >
    <br><br>
    <input type="submit" value="Upload" name="submit">
</form>

PHP脚本如下所示:         

$error = null;
$success = null;
$info = [];
$uploadOk = 1;


$allowedMimes = ['video/mp4', 'image/jpg'];

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

    $counter = 0;
    foreach ( $_FILES['fileToUpload1']['name'] as $file ):
        $target_file = UPLOAD_DIR . basename($file);
        if ( in_array(mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter]), $allowedMimes) ){
            if (move_uploaded_file($_FILES['fileToUpload1']["tmp_name"][$counter], $target_file)) {
                $info[] = "File ".++$counter."($file) uploaded successfully";
            }else {
                $info[] = "File ".++$counter."($file) cannot be uploaded";
            }
        } else {
            $info[] = "File ".++$counter. " is not allowed.";
        }

    endforeach;    
} else {
    echo "upload a file.";
}


?>


    <ul>
    <?php foreach($info as $i){ ?>
    <li><?=$i;?></li>
    <?php }?>
</ul>
<? } ?>

1 个答案:

答案 0 :(得分:1)

moment-timezone文件的mimetype实际上是jpg(而不是image/jpeg),因此如果您尝试上传iamge/jpg个文件,则应更改jpg变量为:

$allowedMimes

此外 - 如果您想支持其他图像类型,您可以使用:

$allowedMimes = ['video/mp4', 'image/jpeg'];

另一种选择 - 如果您想支持所有图片/音频/视频类型,您只能检查字符串的第一部分:

$allowedMimes = ['video/mp4', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp'];

如果您使用的是php&gt; = 5.4,则可以使用:

$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
    array_shift(
        explode("/", 
            mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
        )
    ),
    $allowedTypes) )