2017-01-01 2 views
0

У меня возникают проблемы с вставкой титров при загрузке изображений с помощью class.upload.php.загружать несколько файлов и титров, используя class.upload.php

Изображение переименовано хорошо, но все изображения имеют одинаковый заголовок, хотя у меня есть настройка отдельных текстовых полей для каждого изображения.

Код:

<form action="" enctype="multipart/form-data" id="form" method="post" name="form" role="form"> 
    <table> 
    <tr> 
     <td><input class="form-control" id="customFieldValue2" name="photo_title[]" type="text"></td> 
     <td><input class="form-control" id="customFieldName2" name="image_field[]" type="file"></td> 
    </tr> 
    <tr> 
     <td><input class="form-control" id="customFieldValue2" name="photo_title[]" type="text"></td> 
     <td><input class="form-control" id="customFieldName2" name="image_field[]" type="file"></td> 
    </tr> 
    </table> 
</form> 

Процессор:

$files = array(); 
       foreach ($_FILES['image_field'] as $k => $l) {      
       foreach ($l as $i => $v) { 
       if (!array_key_exists($i, $files)) 
        $files[$i] = array(); 
        $files[$i][$k] = $v; 
       } 
       } 
        $hitung=0; 
        foreach ($files as $file) 
        { 
         $handle = new Upload($file); 
         if ($handle->uploaded) 
         { 
          $hitung++; 
          $newname = $t_timestamp."_".$hitung; 
          $handle->file_new_name_body = $newname; 
          $handle->Process("../uploaded/");  
          if ($handle->processed) 
          { 
           $filename=$newname.".jpg"; 
           $query ="INSERT INTO tbl_report_photos SET 
           photo_title='".$filename."', 
           photo_link='".$filename."', 
           photo_unique='".$aid."'"; 

           if ($sql = mysqli_query($con,$query)) 
           { 
            echo "<script>alert('Report Updated');window.location.href='index.php';</script>"; 
           }  
          } 
          else 
          { 
           echo 'Error: ' . $handle->error;  
          } 
         } 
         else 
         {  
          echo 'Error: ' . $handle->error; 
         } 
         unset($handle); 
        } 

Я редактировал код. он имеет один цикл меньше

ответ

0

Причина, по которой у вас есть одно и то же название, находится в собственном цикле, который не создает переменную, а переписывает себя. Сделать это массив, а затем написать соответствующий ключ:

$taitel[$i] = $_POST['photo_title'][$i]; 

Вы так много петель происходит, это трудно предложить самое лучшее место, чтобы поместить его в свой сценарий.



EDIT: Поскольку у вас возникли проблемы с настройкой этого, я дам демонстрацию. Есть множество вещей, которые я могу попробовать. Во-первых, я бы создал наблюдателя файлов и два, создав расширенный класс вашего класса Uploads. Это одна кажется немного неудобно:

UploadObserver.php

/* 
** @description This will take over for a couple of pieces of your script 
*/ 
class UploadObserver 
    { 
     private $Upload; 
     /* 
     ** @description Pass your database. I like PDO and know it better so I am using that connection 
     **     You would have to change this to accept your MySQLi connection 
     */ 
     public function __construct(\PDO $con) 
      { 
       $this->con = $con; 
      } 
     /* 
     ** @description Create a new instance of a version of the Upload class 
     */ 
     public function upload($file) 
      { 
       # Create a new instance of our extended class 
       $this->Upload = new \PowerUpload($file); 
       # Return it for use 
       return $this->Upload; 
      } 
     /* 
     ** @description This is the class that will process the files array 
     */ 
     public function getFiles($key = 'image_field') 
      { 
       $files = array(); 
       foreach ($_FILES[$key] as $k => $l) {      
        foreach ($l as $i => $v) { 
         if (!array_key_exists($i, $files)) 
          $files[$i]  = array(); 

         $files[$i][$k] = $v; 
        } 
       } 
       # Send back formatted array 
       return $files; 
      } 
     /* 
     ** @description Checks to see if the files array has files 
     */ 
     public function filesSet($key = 'image_field') 
      { 
       return (!empty($_FILES[$key])); 
      } 
     /* 
     ** @description This will write the row to your database 
     */ 
     public function saveToDb($settings) 
      { 
       # Make sure to prepare and bind your values just in case 
       $sql ="INSERT INTO tbl_report_photos SET 
       photo_title = ?, 
       photo_link = ?, 
       photo_unique = ?"; 

       $query = $this->con->prepare($sql); 
       $query->execute($settings); 
      } 
     /* 
     ** @description You could store this in a View class, but for sake of ease I included it here 
     */ 
     public function getSuccess() 
      { 
       ob_start(); 
      ?> 
      <script> 
       alert('Report Updated'); 
       window.location.href = 'index.php'; 
      </script> 
      <?php 
       $data = ob_get_contents(); 
       ob_end_clean(); 

       return $data; 
      } 
    } 

upload.php

Это только предположение о том, что этот класс будет выглядеть на основе того, что вы показали, в вашем примере.

class Upload 
    { 
     public $uploaded, 
       $file_new_name_body, 
       $processed, 
       $error; 

     protected $filename, 
        $fileArray; 

     public function __construct($fileArray) 
      { 
       $this->fileArray = $fileArray; 
      } 

     public function process($path) 
      { 
       if(!is_dir($path)) 
        mkdir($path,0755,true); 

       if(empty($this->file_new_name_body)) 
        $this->file_new_name_body = $this->fileArray['name']; 

       $this->error  = $this->fileArray['error']; 
       $this->processed = move_uploaded_file($this->fileArray['tmp_name'],str_replace('//','/',$path.'/'.$this->file_new_name_body)); 

       if(!$this->processed) 
        throw new \Exception("File was unable to upload."); 
      } 
    } 

PowerUpload.php

/* 
** @description If you can, I would extend the Upload class and save some more readable methods to it 
*/ 
class PowerUpload extends Upload 
    { 
     public function setNewFile($fileArray) 
      { 
       $this->fileArray = $fileArray; 
       return $this; 
      } 

     public function setFileName($name) 
      { 
       $this->file_new_name_body = $name; 

       return $this; 
      } 

     public function checkHasUploaded() 
      { 
       $files = (!empty($this->fileArray)); 

       if(!$files) 
        throw new \Exception("File array can not be empty."); 

       return $files; 
      } 

     public function hasProcessed() 
      { 
       return $this->processed; 
      } 

     public function processUpload($path) 
      { 
       $this->process($path); 
      } 

     public function getError() 
      { 
       return $this->error; 
      } 
    } 

Пересмотренный сценарий на основе изменений: Обратите внимание, что имена формы ввода имеют фактические значения ключей, так что вы можете совпасть файлы с именами проще.

# Create the upload observer, $con is your database connection 
$Uploader  = new UploadObserver($con); 
# If there are files uploading 
if($Uploader->filesSet()) { 
    # Create a loop from the new array 
    # Keep the $key value to match it up with the files value 
    foreach($Uploader->getFiles() as $key => $file) { 
     # Use a try because the uploader submits exceptions on failures 
     try { 
      # Set the name 
      $newname = $t_timestamp."_".$key; 
      # Tag on the extension 
      $filename = $newname.".jpg"; 
      # Create the upload instance 
      $handle  = $Uploader->upload($file); 
      # This will throw exception if failed 
      $handle->checkHasUploaded(); 
      # Assign the file name and upload the file to folder 
      $handle->setFileName($newname)->processUpload(realpath(__DIR__.'/..').'/uploaded/'); 
      # Save the file info to your database using the connection passed originally 
      # You should throw exception here on database fail, PDO does it automatically so it's caught 
      $Uploader->saveToDb(array($_POST['photo_title'][$key],$filename,$aid)); 
      # Create javascript view 
      echo $Uploader->getSuccess(); 
     } 
     # Catch error(s) from the non-db classes  
     catch(\Exception $e) { 
      echo 'Error: '.$e->getMessage(); 
     } 
     # Catch error(s) from the db classes 
     catch(\PDOException $e) { 
      echo 'Error: '.$e->getMessage(); 
     } 
    } 
} 
?> 
<form method="post" enctype="multipart/form-data" action="<?php echo $this->getDataNode('_SERVER')->REQUEST_URI ?>"> 
    <table> 
     <tr> 
      <td><input class="form-control" id="customFieldValue2" name="photo_title[1]" type="text"></td> 
      <td><input class="form-control" id="customFieldName2" name="image_field[1]" type="file"></td> 
     </tr> 
     <tr> 
      <td><input class="form-control" id="customFieldValue2" name="photo_title[2]" type="text"></td> 
      <td><input class="form-control" id="customFieldName2" name="image_field[2]" type="file"></td> 
     </tr> 
    </table> 
    <input type="submit" value="SAVE" /> 
</form> 
+0

спасибо за внимание, я отредактировал код. теперь он имеет еще один цикл. однако я до сих пор не знаю, как создать массив для $ _POST ['photo_title']. – musaspot

Смежные вопросы