4

我正在使用一个表单让用户将文件上传到我的网站。我想让他们一次上传多张照片,所以我使用了 HTML5 的“multiple”属性。

我的 HTML:

<form method="post" action="save.php">
    <input type="file" name="uploads[]" multiple="multiple" />
    <input type="submit" name="submit" value="submit"/>
</form>

保存.php:

<?php
  foreach ($_FILES['uploads']['name'] as $file) {
    echo $file . "<br/>";
    $file= time() . $_FILES['uploads']['name'];
    $target= UPLOADPATH . $file;
    move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
    or die('error with query 2');
   }

但是,由于某种原因,当我运行脚本时,我收到一条错误消息,提示未定义索引:上传。还有一个错误说我为 foreach() 提供了一个无效的参数。我怎么可能错了?

谢谢

更新

好的,设置enctype="mulitpart/form-data"工作。现在,我在移动文件时遇到了麻烦。我收到错误消息move_uploaded_file() expects parameter 1 to be string, array given。我在这里做错了什么?

再次感谢

4

4 回答 4

5

您需要适当enctype的权限才能上传文件。

<form method="post" enctype="multipart/form-data" action="save.php">
于 2012-10-19T14:49:26.003 回答
0

为了首先上传文件,您需要enctype="multipart/form-data"<form>标签上。

但是,当您上传多个文件时,每个键$_FILES['uploads']都是一个数组(就像$_FILES['uploads']['name'])。

循环时需要获取数组键,这样就可以处理每个文件。有关更多详细信息,请参阅文档move_uploaded_file

<?php
  foreach ($_FILES['uploads']['name'] as $key=>$file) {
    echo $file."<br/>";
    $file = time().$file;
    $target = UPLOADPATH.$file;
    move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
    or die('error with query 2');
}
于 2012-10-19T14:58:16.160 回答
0

试试这个 html 代码: <form method="post" action="save.php" enctype="multipart/form-data"> 然后在 PHP 中:

if(isset($_FILES['uploads'])){
foreach ($_FILES['uploads']['name'] as $file) {
    echo $file . "<br/>";
    $file= time() . $_FILES['uploads']['name'];
    $target= UPLOADPATH . $file;
    move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
    or die('error with query 2');
   }
} else {
   echo 'some error message!';
}
于 2012-10-19T14:50:26.460 回答
0

索引.html

<form method="post" action="save.php" enctype="multipart/form-data">
    <input type="file" name="uploads[]" multiple="multiple" />
    <input type="submit" name="submit" value="Upload Image"/>
</form>

保存.php

<?php    
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) {                

      $file_name   = time() . $_FILES['uploads']['name'][$x];
      $file_tmp    = $_FILES['uploads']['tmp_name'][$x];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name;

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";   
      }                 

    }               
  }    
?>
于 2017-11-18T08:03:30.223 回答