2011-05-12 102 views
0

我使用zend窗体上传图片。zend框架窗体上传编辑问题

我的问题是编辑窗体中的信息时,所有的信息,但file_path是空的,所以当你点击提交发生的更新设置file_path为空。

我只想在加载时查看可编辑项目的路径,所以当您单击提交时,旧路径将在那里。

public function EditaddAction() { 

    $session = new Zend_Session_Namespace('user'); 
    $userid = $session->id; 
    // in case the request was an edit request 
    $id = (int) $this->_request->getParam('id'); 
    //The incoming request 
    $request = $this->getRequest(); 
    //initialize form 
    $form = new Admin_Form_Banner(); 
    //uploaded file settings 
    $file = $form->file_path; 
    $file->setDestination(ZendX_Image::getFullUploadPath() . '/files/get/original/'); 
    //instance of db 
    $db = Zend_Db_Table::getDefaultAdapter(); 

    if ($this->getRequest()->isPost()) { 
     if ($form->isValid($request->getPost())) { 

      $dbFilePath = "/files/get/original/" . $file->getFileName(null, false); 


      //code to get the duration of the video 
      $sourceVideo = PUBLIC_PATH . $form->getValue('file_path'); 
      ob_start(); 
      passthru("ffmpeg -i \"" . $sourceVideo . "\" 2>&1"); 
      $duration = ob_get_contents(); 
      ob_end_clean(); 
      preg_match('/Duration: (.*?),/', $duration, $matches); 
      $duration = $matches[1]; 
      $duration_array = preg_split('[:]', $duration); 
      $duration = $duration_array[0] * 3600 + $duration_array[1] * 60 + $duration_array[2]; 

      die($time); 
      end of code to get the duration of the video 
      if (isset($id) && $id != "" && $file->receive()) { 
       try { 
        $db->update('banner', array('banner_title' => $form->getValue('banner_title'), 
         'banner_type' => $form->getValue('banner_type'), 
         'banner_position' => $form->getValue('banner_position'), 
         'banner_link' => $form->getValue('banner_link'), 
         'link_open' => $form->getValue('link_open'), 
         'file_path' => $dbFilePath, 
         'is_active' => $form->getValue('is_active') 
          ), array('id =?' => $id)); 
        $this->flash('Banner Updated', 'admin/banner'); 
       } catch (Exception $e) { 
        $this->flash($e->getMessage(), 'admin/banner'); 
       } 
      } else { 
       try { 

        $db->insert('banner', array('banner_title' => $form->getValue('banner_title'), 
         'banner_type' => $form->getValue('banner_type'), 
         'banner_position' => $form->getValue('banner_position'), 
         'banner_link' => $form->getValue('banner_link'), 
         'link_open' => $form->getValue('link_open'), 
         'file_path' => $dbFilePath, 
         'is_active' => $form->getValue('is_active'), 
         'created_by' => $userid, 
         'date_ceated' => date('Y/m/d H:i:s'), 
         'is_deleted' => 0, 
        )); 
        $this->flash('Banner Added', 'admin/banner'); 
       } catch (Exception $e) { 
        $this->flash($e->getMessage(), 'admin/banner'); 
       } 
      } 
     } 
    } 

    if (isset($id) && $id != "") { 
     $checkvalues = $db->fetchCol($db->select()->from(array('banner'),array('file_path'))); 
     $values = $db->fetchRow("SELECT * FROM banner WHERE id = ?", $id); 
     $values['file_path'] = $checkvalues; 
     $form->populate($values); 
    } 

    $this->view->form = $form; 
+0

我会将该描述编辑为多个句子和段落,以便人们有机会阅读它! – Treffynnon 2011-05-12 12:24:49

+0

在更新时不要覆盖数据库中的值,除非它已被提供? – Treffynnon 2011-05-12 12:35:37

+0

我这样做仍然是相同的问题 – haider 2011-05-12 12:41:37

回答

1

当你说路径你的意思是在http客户端的路径? 您无权访问该文件。

如果你的问题是关于文件路径上传您可以按以下做后:

1)的元素必须是Zend_Form_Element_File。

2)控制器:

$form->file_path->receive(); //this will return true if the file was successfully received and false if not 
$file_path_on_server = $form->file_path->getFileName(); // there you get the file name 

该文件将保持其原来的名字。

+0

当我尝试你的第一个代码和var_dump它。我得到了一个虚假的信息,这意味着它正在检索什么,你知道为什么吗? – haider 2011-05-13 18:43:18

+0

错误表示文件未成功接收。不要忘记设置Zend_Form_Element_File的目的地(_ $ element-> setDestination('path')_) – pantunas 2011-06-02 13:44:05

1

我遇到了同样的问题。 我解决它使用一个隐藏字段,形式,我在其中存储的文件名,并在修改操作使用

some action code 
if ($request->isPost()) { 
       if ($form->isValid($request->getPost())) { 
        if ('administrator' == $user->role) { 
         $oldFileName = $form->getElement('oldfilename')->getValue(); //the hidden field 
         $data = $form->getValues(); 
         $model->populate($data); 
        if (file_exists('uploads/cv/' . $oldFileName)) { 
          $form->getElement('cv')->setIgnore(true); //this is my Form File Element - the file exists, I don't need to store the filename 
         } else { // if you want you can unlink $oldFileName 
          $upload = new Zend_File_Transfer_Adapter_Http(); 
          $info = $upload->getFileInfo('cv'); 
          $upload->setDestination("uploads/cv/"); 
          if (file_exists('uploads/cv/' . $info['cv']['name'])) { 
           $newFileName = time() . rand(0, 100000) . "-" . $info['cv']['name']; // I need to avoid overwriting file 
          } else { 
           $newFileName = $info['cv']['name']; 
           $upload->addFilter('Rename', $newFileName); 
          } 
          try { 
           $upload->receive(); 
          } catch (Zend_File_Transfer_Exception $e) { 
           $e->getMessage(); 
          } 
         } 
         $model->save(); 
         return $this->_helper->redirector('list'); 
        } else { 
         //some error message 
         $this->_helper->redirector('list'); 
        } 
       } else { //form not valid 
        $this->view->form = $form; 
       } 
      } else { 
       $model->find($id); 
       $data = array(); 
       $data = $model->toArray(); 
       $data['oldfilename'] = $model->get_cv(); //the filename stored in db 
       $form->getElement('cv')->setRequired(false); 
       $form->populate($data); 
       $this->view->form = $form; 
      } 

肯定有很多事情可以固定一个更好的编程..

0
public function addAction() 
    { 

     // Criação do Objeto Formulário 
     $form = new Application_Form_Banner(); 
     $banners = new Application_Model_Banners(); 
     // Há dados para Tratamento? 
     if ($this->getRequest()->isPost()) { 

      // Pegamos os Dados como Foram Enviados 
      $data = $this->getRequest()->getPost(); 
      $path = APPLICATION_PATH . '/../public/banners/'; 
      if (!is_dir($path)) { 
       mkdir($path, 0777, true); 
      } 
      if ($form->isValid($data)) { 

       try { 
        // Dados Filtrados pelo Formulário 
        $banners->getAdapter()->beginTransaction(); 
        //gambi para renomear arquivos 
        $upload = new Zend_File_Transfer_Adapter_Http(); 
//    $upload->addValidator('Size', false, array('min' => 100, 
//     'max' => 1150000, 
//     'bytestring' => true)); 
        $upload->addValidator('ImageSize', false, array(
         'minwidth' => 10, 'minheight' => 10, 
         'maxwidth' => 5500, 'maxheight' => 5500)); 
        $filename = $upload->getFilename(); 
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); 
        $filename = basename($filename); 
        $newfilename = mt_rand() . '.' . $ext; 
        $upload->addFilter(new Zend_Filter_File_Rename(array('target' => $path . $newfilename, 'overwrite' => false))); 
        if (!$upload->isValid()) { 
         $this->_flashMessenger->addMessage(array('error' => 'O tamanho arquivo é muito grande.')); 
        } 
        if ($upload->receive()) { 

         //Para funcionar esse metodo $form->getValues(); precisa ficar abaixo do método $upload->receive() 
         $data = $form->getValues(); 
         $data['banner_imagem'] = $newfilename; 
         // Qualquer Manipulação de Dados 
         $banners->insert($data); 
         $banners->getAdapter()->commit(); 
         $form->reset(); //limpa os campos do form. 
         $this->_flashMessenger->addMessage(array('success' => 'Dados salvos com sucesso!')); 
        } 
       } catch (Exception $e) { 
        $this->_flashMessenger->addMessage(array('error' => $e->getMessage())); 
       } catch (Zend_File_Transfer_Exception $e) { 
        $this->_flashMessenger->addMessage(array('error' => $e->getMessage())); 
       } catch (Zend_Db_Table_Exception $e) { 
        $banners->getAdapter()->rollBack(); 
        $this->_flashMessenger->addMessage(array('error' => $e->getMessage())); 
       } 
      } else { 
       $form->populate($data); 
      } 
     } 
     // Envio para a Camada de Visualização 
     $this->view->form = $form; 
    } 

    public function editAction() 
    { 
     // Criação do Objeto Formulário 
     $form = new Application_Form_Banner(); 
     $banners = new Application_Model_Banners(); 
     $form->getElement('banner_imagem')->setRequired(false); 
     $form->getElement('banner_imagem')->setIgnore(true); 

     $id = $this->_request->getParam('id'); 
     $data = $banners->find($id)->current()->toArray(); 
     $path = APPLICATION_PATH . '/../public/banners/'; 
     $banner_imagemdb = $data['banner_imagem']; 
//  Zend_Debug::dump($form->getValues()); 
     // Há dados para Tratamento? 
     if ($this->getRequest()->isPost()) { 

      // Pegamos os Dados como Foram Enviados 
      $data = $this->getRequest()->getPost(); 

//   $data = $form->getValues(); 
//   Zend_Debug::dump($this->getRequest()->getPost()); 
//   print($form->getValue('banner_imagem')); 
//   $banner_imagem = $form->getValue('banner_imagem'); 


      if (!is_dir($path)) { 
       mkdir($path, 0777, true); 
      } 
      if ($form->isValid($data)) { 
//    Zend_Debug::dump($this->getRequest()->getPost()); 
       try { 

        // Dados Filtrados pelo Formulário 
        $banners->getAdapter()->beginTransaction(); 
//     Zend_Debug::dump($banner_imagem); 
        if ($form->banner_imagem->isUploaded()) { 
         //gambi para renomear arquivos 
         $upload = new Zend_File_Transfer_Adapter_Http(); 
         $upload->addValidator('Size', false, array('min' => 100, 
          'max' => 11150000, 
          'bytestring' => true)); 
         $upload->addValidator('ImageSize', false, array(
          'minwidth' => 10, 'minheight' => 10, 
          'maxwidth' => 5500, 'maxheight' => 5500)); 
         $filename = $upload->getFilename(); 
         $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); 
         $filename = basename($filename); 
         $newfilename = mt_rand() . '.' . $ext; 
         $upload->addFilter(new Zend_Filter_File_Rename(array('target' => $path . $newfilename, 'overwrite' => false))); 
         if (!$upload->isValid()) { 
          $this->_flashMessenger->addMessage(array('error' => 'O tamanho arquivo é muito grande.')); 
         } 
         if ($upload->receive()) { 
          //apaga imagem antiga    
          @unlink($path . $banner_imagemdb); 

          //Para funcionar esse metodo $form->getValues(); precisa ficar abaixo do método $upload->receive() 
          $data = $form->getValues(); 
          $data['banner_imagem'] = $newfilename; 
          // Qualquer Manipulação de Dados 
          $where = $banners->getAdapter()->quoteInto("banner_id = ?", $id); 
          $banners->update($data, $where); 
          $banners->getAdapter()->commit(); 
          $form->reset(); //limpa os campos do form. 
          $this->_flashMessenger->addMessage(array('success' => 'Dados salvos com sucesso!')); 
         } 
        } else { 
         $form->getElement('banner_imagem')->setRequired(false); 
         $form->getElement('banner_imagem')->setIgnore(true); 
         //Para funcionar esse metodo $form->getValues(); precisa ficar abaixo do método $upload->receive() 
         $data = $form->getValues(); 
         $data['banner_imagem'] = $banner_imagemdb; 
         // Qualquer Manipulação de Dados 
         $where = $banners->getAdapter()->quoteInto("banner_id = ?", $id); 
         $banners->update($data, $where); 
         $banners->getAdapter()->commit(); 
         $form->reset(); //limpa os campos do form. 
         $this->_flashMessenger->addMessage(array('success' => 'Dados salvos com sucesso!')); 
        } 
       } catch (Exception $e) { 
        $this->_flashMessenger->addMessage(array('error' => $e->getMessage())); 
       } catch (Zend_File_Transfer_Exception $e) { 
        $this->_flashMessenger->addMessage(array('error' => $e->getMessage())); 
       } catch (Zend_Db_Table_Exception $e) { 
        $banners->getAdapter()->rollBack(); 
        $this->_flashMessenger->addMessage(array('error' => $e->getMessage())); 
       } 
      } 
     } 

//  Zend_Debug::dump($data); 
     $form->populate($data); 
     $imagePreview = $form->createElement('image', 'image_preview'); 
// element options 
     $imagePreview->setLabel('Preview Image: '); 
     $imagePreview->setAttrib('style', 'width:200px;height:auto;'); 
// add the element to the form 
     $imagePreview->setOrder(4); 
     $imagePreview->setImage('/public/banners/' . $data['banner_imagem']); 

     $form->addElement($imagePreview); 


     // Envio para a Camada de Visualização 
     $this->view->form = $form; 
    } 

    assim da certo