【问题标题】:Count dir and rename multiple uploaded files on upload.在上传时计算目录并重命名多个上传的文件。
【发布时间】:2014-04-15 06:25:14
【问题描述】:

我正在尝试从一个表单上传多个文件 (imgs),我想获取它们将被上传到的目录的计数,然后相应地重命名它们。 1.jpg、2.jpg、3.jpg 等取决于上传的数量。我最接近的是让它重命名和上传第一个文件。

<?php
$foldername = $_POST['stock'];

$path = 'vehicles/' . $foldername;
mkdir($path);
?>

<?php
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 10240*1000; //100 kb
$path = "vehicles/$stock/"; // Upload directory
$count = 0;

$directory = "vehicles/$stock/";
$filecount = 0;
$files = glob($directory . "jpg");
if ($files){
  $filecount = count($files);
}

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
  // Loop $_FILES to execute all files
  foreach ($_FILES['files']['name'] as $f => $name) {     
    if ($_FILES['files']['error'][$f] == 4) {
      continue; // Skip file if any error found
    }        
    if ($_FILES['files']['error'][$f] == 0) {            
      if ($_FILES['files']['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 
        $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
        $uniq_name = uniqid() . '.' .'jpg';
        move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path .              $uniq_name);
        $count++; // Number of successfully uploaded file
      }
    }
  }
}
?>

【问题讨论】:

    标签: php file-upload count rename dir


    【解决方案1】:

    您的 foreach 正在遍历第一个文件。您想要循环遍历所有文件的内容。

    foreach ($_FILES as $file_input){
    }
    

    【讨论】:

      【解决方案2】:

      我的意思是你在文件名构造函数中的错误:

         $uniq_name = ($filecount+1) . '.' .$ext;
      
         if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$uniq_name)) {
             $count++; // Number of successfully uploaded file
             $filecount++; //Folders files count
         } else {
             $message[] = "$name is not uploaded";
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-24
        • 2017-03-19
        相关资源
        最近更新 更多