2016-04-28 4 views
-1

У меня проблема с несколькими загрузками файлов в cakephp.PHP-код для загрузки нескольких файлов с базой данных

Я пытаюсь загрузить несколько файлов и вам нужно вставить несколько записей в таблицу, но я не могу этого сделать.

Для Ex - если я загружаю 3 фотографии из формы, тогда вам необходимо вставить 3 строки в таблицу со своим именем файла.

public function add() { 
      $this->Driver->create(); 
      if ($this->request->is('post')) { 
        for($i=1;$i<4;$i++) 
        { 
         if(empty($this->data['Driver']['document'.$i]['name'])){ 
          unset($this->request->data['Driver']['document'.$i]); 
         } 

         if(!empty($this->data['Driver']['document'.$i]['name'])) 
         { 
          $file=$this->data['Driver']['document'.$i]; 
          $ary_ext=array('jpg','jpeg','xls','docx'); //array of allowed extensions 
          $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension 
          if(in_array($ext, $ary_ext)) 
          { 
           move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. time().$file['name']); 
           $this->request->data['Driver']['document'.$i] = time().$file['name']; 
          } 
         } 

        } 

       if ($this->Driver->save($this->request->data)) 
       { 
        //echo "<pre>";print_r($this->request->data); exit(); 
        $this->Session->setFlash('Your post has been saved.'); 
        $this->redirect(array('action' => 'add')); 
       } 
       else 
       { 
        $this->Session->setFlash('Unable to add your post.'); 
       } 
      } 
     } 

add.ctp 


    <h1>Add Post</h1><?php 
    echo $this->Form->create('Driver', array('url' => array('action' => 'add'), 'enctype' => 'multipart/form-data')); 
    echo $this->Form->input('address',array('div' => false, 'class' => 'form-control user-name')); 
    for($i=1; $i<4; $i++) 
    { 
    ?> 


<div id="attachment<?php echo $i;?>" <?php if($i !=1) echo "style='display:none;'";?> > 
      <div> 
      <?php echo $this->Form->input('document'.$i,array('type'=>'file','label' => false,'div' => false));?> 

      </div> 
      <div id="attachmentlink<?php echo $i;?>" <?php if($i==3) echo "style='display:none;'";?>><a href="javascript:void(0);" onclick="show('attachment<?php echo $i+1;?>'); hide('attachmentlink<?php echo $i;?>');">Add Another Attachment</a></div> 
      </div> 
      <?php } ?> 

<?php 
echo $this->Form->end('Save'); 
?> 
+0

Что * вопрос * точно? Вам нужно сузить проблему и предоставить более подробную информацию, вы получите сообщение об ошибке и т. Д.? – jeroen

+1

Тот же вопрос http://stackoverflow.com/questions/36888022/php-code-to-upload-multiple-images-cakephp – Salines

+0

Мне нужно, чтобы я выбрал 3 изображения из моей формы, затем необходимо вставить 3 строки в databse .. .if, чтобы выбрать 2 изображения, затем необходимо вставить 2 строки в базу данных, например мудрый. –

ответ

0

Plz попробовать это

public function add() { 
    $this->Driver->create(); 
    if ($this->request->is('post')) { 
      for($i=1;$i<4;$i++) 
      { 
       if(empty($this->data['Driver']['document'][$i]['name'])){ 
        unset($this->request->data['Driver']['document'.$i]); 
       } 

       if(!empty($this->data['Driver']['document'][$i]['name'])) 
       { 
        $file=$this->data['Driver']['document'][$i]; 
        $ary_ext=array('jpg','jpeg','xls','docx'); //array of allowed extensions 
        $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension 
        if(in_array($ext, $ary_ext)) 
        { 
         move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. time().$file['name']); 
         $this->request->data['Driver']['document'][$i] = time().$file['name']; 
        } 
       } 

      } 

     if ($this->Driver->save($this->request->data)){ 
      $this->Session->setFlash('Your post has been saved.'); 
      $this->redirect(array('action' => 'add')); 
     }else{ 
      $this->Session->setFlash('Unable to add your post.'); 
     } 
    } 
} 
+0

нет, это не так, как мой код .... –

+0

Я изменил в $ this-> data ['Driver'] ['document'] [ $ я]; –

0

CakePHP 2 Field naming conventions

echo $this->Form->input('Modelname.0.fieldname'); 
echo $this->Form->input('Modelname.1.fieldname'); 

в файле вида

//for($i=1; $i<4; $i++).. 
echo $this->Form->input('Driver.'.$i.'.document', array('type' => 'file')); 

в контроллере, как

$this->request->data['Driver'][$i]['document']['name'] // where name is uploaded document filename 

Использование Model::saveMany(array $data = null, array $options = array())

Метод используется для сохранения нескольких строк одной и той же модели, сразу ...

if ($this->Driver->saveMany($this->request->data))... 

UPDATE код

<?php 

public function add() 
{ 
    if ($this->request->is('post')) { 
     for($i=1;$i<4;$i++) 
     { 
      if(empty($this->request->data['Driver'][$i]['document']['name'])){ 
       unset($this->request->data['Driver'][$i]['document']); 
      } 

      if(!empty($this->request->data['Driver'][$i]['document']['name'])) 
      { 
       $time = time(); // <------------- 
       $file=$this->request->data['Driver'][$i]['document']; 
       $ary_ext=array('jpg','jpeg','xls','docx'); //array of allowed extensions 
       $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension 
       if(in_array($ext, $ary_ext)) 
       { 
        move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. $time.$file['name']); 
        $this->request->data['Driver'][$i]['document'] = $time.$file['name']; 
       } 
      } 

     } 
     $this->Driver->create(); 
     if ($this->Driver->saveMany($this->request->data)) 
     { 
      //echo "<pre>";print_r($this->request->data); exit(); 
      $this->Session->setFlash('Your post has been saved.'); 
      $this->redirect(array('action' => 'index')); 
     } 
     else 
     { 
      $this->Session->setFlash('Unable to add your post.'); 
     } 
    } 
} 

add.ctp

<h1>Add Post</h1> 
<?php 
    echo $this->Form->create('Driver', array('type' => 'file')); 
    //echo $this->Form->input('address',array('div' => false, 'class' => 'form-control user-name')); ???? 
    for($i=1; $i<4; $i++) 
    { 
    ?> 


<div id="attachment<?php echo $i;?>" <?php if($i !=1) echo "style='display:none;'";?> > 
      <div> 
      <?php echo $this->Form->input('Driver.'.$i.'.document',array('type'=>'file','label' => false,'div' => false));?> 

      </div> 
      <div id="attachmentlink<?php echo $i;?>" <?php if($i==3) echo "style='display:none;'";?>><a href="javascript:void(0);" onclick="show('attachment<?php echo $i+1;?>'); hide('attachmentlink<?php echo $i;?>');">Add Another Attachment</a></div> 
      </div> 
      <?php } ?> 

<?php 
echo $this->Form->end('Save'); 
?> 
+0

нет его не работает –

+0

использовать $ this-> request-> данные [.... – Salines

+0

Я обновляю свой ответ – Salines

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