在不同的字段中上传多个文件

时间:2014-07-31 14:38:10

标签: php html html5 upload

我在从表单上传一堆文件时遇到了麻烦。我需要单独创建输入字段,我的表单是这样的:

<form action="upload.php" method="post" id="form" name="form" enctype="multipart/form-data">

  <input type="file" name="upload[]" >
  <input type="file" name="upload[]" >
  ...(more inputs)
  <input type="file" name="upload[]" >

  <button id="submit-button">Upload</button>

</form>

我在这个项目中使用jQuery 1.9除了上传之外的任何其他内容,我似乎无法找到任何适合我尝试做的事情。我找到了很多多输入内容,但是这样我就无法将每个文件区分开来,我需要将每个文件的url保存到我的DB中的右列。

我已经使用了我在其他类似问题上找到的一些代码,但它们似乎并不起作用。我现在尝试过这个:

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ((array)$_FILES['upload']['name'] as $f => $name) {     
    if ($_FILES['upload']['error'][$f] == 4) {
        continue; // Skip file if any error found
    }          
    if ($_FILES['upload']['error'][$f] == 0) {             
        if ($_FILES['upload']['size'][$f] > $max_file_size) {
            $message[] = "$name is too large!.";
            continue; // Skip large files
        }
        elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
            $message[] = "$name is not a valid format";
            continue; // Skip invalid file formats
        }
        else{ // No error found! Move uploaded files 
            if(move_uploaded_file($_FILES["upload"]["tmp_name"][$f], $path.$name))
            $count++; // Number of successfully uploaded file
        }
    }
}
}

我什么都不知道,我尝试上传的文件并没有显示在服务器上。我已经使用php_info()进行了检查,似乎上传功能已启用,因为我上传的是.pdf,只需&#34;测试&#34;写在它上面约7kb,我认为尺寸不是这里的问题。

我希望你们能帮助我,谢谢。

更新

我删除了(数组)转换,我遇到以下错误:

  

警告:在path_of_file

中为foreach()提供的参数无效

1 个答案:

答案 0 :(得分:2)

你遗漏了非常重要的元素enctype

enctype='multipart/form-data'

在表单标记中使用此选项并再次检查。

<form action="upload.php" method="post" enctype='multipart/form-data' id="form" name="form">

- &GT;对于您的错误,请使用以下代码(已更新)上传多个图像

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files

foreach ($_FILES['username']['name'] as $f => $name) {

    $path = 'uploads'; //path of directory

    if ($_FILES['username']['error'][$f] == 4) {
        continue; // Skip file if any error found
    } else {
        if ($_FILES['username']['size'][$f] > $max_file_size) {
            $message[] = "$name is too large!.";
            continue; // Skip large files
        }
        elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
            $message[] = "$name is not a valid format";
            continue; // Skip invalid file formats
        }
        else {
            // No error found! Move uploaded files 
            //$name_of_file = $_FILES['username']['name'][$f];
            $temp_name = $_FILES['username']['tmp_name'][$f]; //[$count];
            move_uploaded_file($temp_name, "$path/"."$name");
            $count++; // Number of successfully uploaded file
        }
    }
}
}