【问题标题】:PHP multiple file upload uploads same image 5 times instead of all filesPHP多个文件上传上传相同的图像5次而不是所有文件
【发布时间】:2013-11-09 02:55:00
【问题描述】:

大家好,我的代码真的很吃力。当我尝试上传多张图片时,它会上传同一张图片 5 次,而不是同时上传两张图片。任何帮助表示赞赏。 感谢您的宝贵时间。

这里是 var_dumb($_FILES)

array(1) {
  ["userfile"]=>
  array(5) {
    ["name"]=>
    string(9) "test1.jpg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpdDGCy2"
    ["error"]=>
    int(0)
    ["size"]=>
    int(1768037)
  }
}

这是我的上传功能:

if(count($_FILES['userfile'])){
    foreach($_FILES['userfile'] as $file){
$alt=mysqli_real_escape_string($conn, $_POST['alt']);
echo '<pre>';
var_dump($_FILES);
echo '</pre>';
if (($_FILES["userfile"]["error"] == 0) && ($_FILES['userfile']['size'] > 0))
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
} 
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["userfiles"]["name"]));
if((($_FILES["userfile"]["type"] == "image/gif")
    ||($_FILES["userfile"]["type"]=="image/jpeg")
    ||($_FILES["userfile"]["type"]=="image/png")
    ||($_FILES["userfile"]["type"]=="image/pjpeg")
    && in_array($extension, $allowedExts)))
    {
        $fp = fopen($tmpName, 'r');
        $content =fread($fp, filesize($tmpName));
        $SourceImage = imagecreatefromstring($content);
        $SourceWidth = imagesx($SourceImage);
        $SourceHeight=imagesy($SourceImage);
        $DestWidth=100;
        $DestHeight=130;
        if ($SourceHeight> $SourceWidth)
        {$ratio = $DestHeight / $SourceHeight;
        $newHeight = $DestHeight;
        $newWidth = $sourceWidth * $ratio;
        }
        else
        {
            $ratio = $DestWidth / $SourceWidth;
            $newWidth = $DestWidth;
            $newHeight = $SourceHeight * $ratio;
        }
        $DestinationImage = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($DestinationImage, $SourceImage, 0,0,0,0,$DestWidth, $DestHeight, $SourceHeight, $SourceWidth);
        ob_start();
        imagejpeg($DestinationImage);
        $BinaryThumbnail = ob_get_contents();
        ob_end_clean();
        $thumb = addslashes($BinaryThumbnail);
        $content = addslashes($content);
        fclose($fp);
        $fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

         mysqli_query($conn, "INSERT INTO files (username, name, size, content, type, link, alt, thumbnail) VALUES ('$username', '$fileName', '$fileSize', '$content', '$fileType', 1, '$alt', '$thumb')") or die('Error, query failed'); 
           echo "<script>alert('The file has been uploaded');location.replace('uploaded.php');</script>";
           unlink ($_FILES['username']['tmp_name']);

    }else{ 
           echo "<script>alert('Please upload an image');location.replace('upload.php');</script>";
    }
}
}
}

这是上传表格:

    <div class="container">
 <div class="row">
  <div class="col-md-6 col-md-offset-3">
          <h1>Upload a file</h1>
<form method="post" enctype="multipart/form-data" action="process.php">
<div id="filediv">
<div id="imagefiles">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<label>Upload File:
<input name="userfile[]" type="file" id="userfile" multiple></label>
<label>Alt Text: <input name="alt" type="text"></label>
 </div>
 </div>
<br>

<input type="button" value="Add Another File" onclick="copyDiv()"/>
<input name="UploadFile" type="submit" />
</form>

【问题讨论】:

  • 你引用 $_FILES['userfile']['name'] inside 你的 foreach 循环;您需要将所有这些引用替换为 $file,因为其中包含您当前正在使用的变量。
  • 所以我做 $fileName = $_FILES $file; $tmpName = $_FILES $文件; $fileSize = $_FILES $file; $fileType = $_FILES $file; ?对不起,我不明白。
  • 你的 foreach 循环遍历文件数组;所以你需要$file['name'];,而不是$_FILES['userfile']['name'];,等等。

标签: php file-upload


【解决方案1】:

在循环中使用来自 foreach 的变量 $file,而不是 $_FILES['userfile']

还可以在$_FILES 上使用var_dump 来检查它是如何发送的。

【讨论】:

    【解决方案2】:

    如果您一次上传多个文件,服务器很可能只接受一个文件。我曾经遇到过这个问题,我通过ajax文件上传修复了它。 Ajax 文件上传也非常有用,因为用户不必等待所有文件都传输到服务器。你可以使用这个。 https://github.com/blueimp/jQuery-File-Upload

    【讨论】:

      【解决方案3】:

      你可以试试for loop 而不是foreach....as:

      if(count($_FILES['userfile'])){
         for($i=0;$i<count($_FILES['userfile']);$i++) {
      $alt=mysqli_real_escape_string($conn, $_POST['alt']);
      echo '<pre>';
      var_dump($_FILES);
      echo '</pre>';
      if (($_FILES["userfile"]["error"] == 0) && ($_FILES['userfile']['size'] > 0))
      {
      $fileName = $_FILES['userfile']['name'][$i];
      $tmpName  = $_FILES['userfile']['tmp_name'][$i];
      $fileSize = $_FILES['userfile']['size'][$i];
      $fileType = $_FILES['userfile']['type'][$i];
      } 
      $allowedExts = array("jpg", "jpeg", "gif", "png");
      $extension = end(explode(".", $_FILES["userfiles"]["name"]));
      if((($_FILES["userfile"]["type"] == "image/gif")
          ||($_FILES["userfile"]["type"]=="image/jpeg")
          ||($_FILES["userfile"]["type"]=="image/png")
          ||($_FILES["userfile"]["type"]=="image/pjpeg")
          && in_array($extension, $allowedExts)))
          {
              $fp = fopen($tmpName, 'r');
              $content =fread($fp, filesize($tmpName));
              $SourceImage = imagecreatefromstring($content);
              $SourceWidth = imagesx($SourceImage);
              $SourceHeight=imagesy($SourceImage);
              $DestWidth=100;
              $DestHeight=130;
              if ($SourceHeight> $SourceWidth)
              {$ratio = $DestHeight / $SourceHeight;
              $newHeight = $DestHeight;
              $newWidth = $sourceWidth * $ratio;
              }
              else
              {
                  $ratio = $DestWidth / $SourceWidth;
                  $newWidth = $DestWidth;
                  $newHeight = $SourceHeight * $ratio;
              }
              $DestinationImage = imagecreatetruecolor($newWidth, $newHeight);
              imagecopyresampled($DestinationImage, $SourceImage, 0,0,0,0,$DestWidth, $DestHeight, $SourceHeight, $SourceWidth);
              ob_start();
              imagejpeg($DestinationImage);
              $BinaryThumbnail = ob_get_contents();
              ob_end_clean();
              $thumb = addslashes($BinaryThumbnail);
              $content = addslashes($content);
              fclose($fp);
              $fp      = fopen($tmpName, 'r');
      $content = fread($fp, filesize($tmpName));
      $content = addslashes($content);
      fclose($fp);
      
               mysqli_query($conn, "INSERT INTO files (username, name, size, content, type, link, alt, thumbnail) VALUES ('$username', '$fileName', '$fileSize', '$content', '$fileType', 1, '$alt', '$thumb')") or die('Error, query failed'); 
                 echo "<script>alert('The file has been uploaded');location.replace('uploaded.php');</script>";
                 unlink ($_FILES['username']['tmp_name'][$i]);
      
          }else{ 
                 echo "<script>alert('Please upload an image');location.replace('upload.php');</script>";
          }
      }
      }
      }
      

      【讨论】:

      • 我尝试了 for 循环。它实际上只从一个文件中提取一个......并且由于某种原因它破坏了我的表格并将文件名分解为数组的每个位置而不是整个文件。当我回显文件数时,即使我只上传了 1 个文件,我也会得到 5 个。 5 array(1) { ["userfile"]=> array(5) { ["name"]=> string(5) "1.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/php7LU76b" ["error"]=> int(0) ["size"]=> int(780831) } }
      【解决方案4】:

      是的,我会考虑在这里使用 JS/AJAX 解决方案,而不是 php。使用 php 上传多个文件有点麻烦,因为在代码执行时加载时间和页面刷新时间很长,并且没有真正反馈给用户关于幕后发生的事情。

      我用过uploadify 几次,效果很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-13
        • 1970-01-01
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        • 2022-12-01
        • 2019-01-29
        相关资源
        最近更新 更多