在 php 中上传多个文件

2022-08-30 06:54:50

我想上传多个文件并将它们存储在一个文件夹中,然后获取路径并将其存储在数据库中...您寻找的任何好例子都用于执行多个文件上传...

注意:文件可以是任何类型的...


答案 1

我知道这是一个旧帖子,但对于试图上传多个文件的人来说,一些进一步的解释可能很有用......以下是您需要执行的操作:

  • 输入名称必须定义为数组,即name="inputName[]"
  • 输入元素必须具有或仅multiple="multiple"multiple
  • 在 PHP 文件中,使用语法"$_FILES['inputName']['param'][index]"
  • 确保查找空文件名和路径,数组可能包含空字符串。计数前使用。array_filter()

下面是一个向下和肮脏的示例(仅显示相关代码)

网页:

<input name="upload[]" type="file" multiple="multiple" />

菲律宾比索:

//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.

// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);

// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {

  //Get the temp file path
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

  //Make sure we have a file path
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

希望这有帮助!


答案 2

可以选择多个文件,

然后使用执行上载的示例 php 脚本上载:<input type='file' name='file[]' multiple>

<html>
<title>Upload</title>
<?php
    session_start();
    $target=$_POST['directory'];
        if($target[strlen($target)-1]!='/')
                $target=$target.'/';
            $count=0;
            foreach ($_FILES['file']['name'] as $filename) 
            {
                $temp=$target;
                $tmp=$_FILES['file']['tmp_name'][$count];
                $count=$count + 1;
                $temp=$temp.basename($filename);
                move_uploaded_file($tmp,$temp);
                $temp='';
                $tmp='';
            }
    header("location:../../views/upload.php");
?>
</html>

所选文件以数组形式接收,其中

$_FILES['file']['name'][0]存储第一个文件的名称。
存储第二个文件的名称。
等等。$_FILES['file']['name'][1]


推荐