Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Problemas na salva de imagens - Upload de imagem no TFile Pessoal, é o seguinte! Estou fazendo uma implementação de acordo com os exemplos do Tutor. Mas por algum motivo (ainda não descobri qual), a imagem não carrega para meu campo Image. Ao tentar salvar o registro dá o seguinte erro: Fatal error: Class 'finfo' not found in C:xampphtdocsctrlarmasappcontrolDivulgacaoForm.class.php on line 126 Em anexo, segue como fica a tela a...
SS
Problemas na salva de imagens - Upload de imagem no TFile  
Pessoal, é o seguinte!

Estou fazendo uma implementação de acordo com os exemplos do Tutor.
Mas por algum motivo (ainda não descobri qual), a imagem não carrega para meu campo Image.

Ao tentar salvar o registro dá o seguinte erro:

Fatal error: Class 'finfo' not found in C:xampphtdocsctrlarmasappcontrolDivulgacaoForm.class.php on line 126


Em anexo, segue como fica a tela após carregar a imagem, e abaixo segue o código da pagina!

  1. <?php
  2. /**
  3.  * DivulgacaoForm Form
  4.  * @author  <your name here>
  5.  */
  6. class DivulgacaoForm extends TPage
  7. {
  8.     protected $form// form
  9.     private   $frame;    
  10.     
  11.     /**
  12.      * Form constructor
  13.      * @param $param Request
  14.      */
  15.     public function __construct$param )
  16.     {
  17.         parent::__construct();
  18.         
  19.         // creates the form
  20.         $this->form = new TQuickForm('form_Divulgacao');
  21.         $this->form->class 'tform'// change CSS class
  22.         $this->form = new BootstrapFormWrapper($this->form);
  23.         $this->form->style 'display: table;width:100%'// change style
  24.         
  25.         // define the form title
  26.         $this->form->setFormTitle('Divulgacao');
  27.         
  28.         // create the form fields
  29.         $id = new TEntry('id');
  30.         $titulo_divulgacao = new TEntry('titulo_divulgacao');
  31.         $data_validade = new TDate('data_validade');
  32.         $caminho_imagem = new TFile('caminho_imagem');
  33.         
  34.         // complete upload action
  35.         $caminho_imagem->setCompleteAction(new TAction(array($this'onComplete')));
  36.         // add the fields
  37.         $this->form->addQuickField('Id'$id,  '30%' );
  38.         $this->form->addQuickField('Titulo Divulgacao'$titulo_divulgacao,  '70%' , new TRequiredValidator);
  39.         $this->form->addQuickField('Data Validade'$data_validade,  '70%' , new TRequiredValidator);
  40.         $this->form->addQuickField('Caminho Imagem'$caminho_imagem,  '70%' );
  41.         $this->frame = new TElement('div');
  42.         $this->frame->id 'photo_frame';
  43.         $this->frame->style 'width:400px;height:auto;min-height:200px;border:1px solid gray;padding:4px;';
  44.         $row $this->form->addRow();
  45.         $row->addCell('');
  46.         $row->addCell($this->frame);        
  47.         if (!empty($id))
  48.         {
  49.             $id->setEditable(FALSE);
  50.         }
  51.         
  52.         /** samples
  53.          $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  54.          $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  55.          $fieldX->setSize( 100, 40 ); // set size
  56.          **/
  57.          
  58.         // create the form actions
  59.         $this->form->addQuickAction(_t('Save'), new TAction(array($this'onSave')), 'fa:floppy-o');
  60.         $this->form->addQuickAction(_t('New'),  new TAction(array($this'onClear')), 'bs:plus-sign green');
  61.         
  62.         // vertical box container
  63.         $container = new TVBox;
  64.         $container->style 'width: 90%';
  65.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  66.         $container->add(TPanelGroup::pack('Cadastro de Divulgacao'$this->form));
  67.         $container->add(TPanelGroup::pack(''$this->frame));
  68.         
  69.         parent::add($container);
  70.     }
  71.     /**
  72.      * Save form data
  73.      * @param $param Request
  74.      */
  75.      
  76.     public static function onComplete($param)
  77.     {
  78.         new TMessage('info''Upload completed: '.$param['caminho_imagem']);
  79.         
  80.         // refresh photo_frame
  81.         TScript::create("$('#photo_frame').html('')");
  82.         TScript::create("$('#photo_frame').append(\"<img style='width:100%' src='tmp/{$param['caminho_imagem']}'>\");");
  83.     }   
  84.      
  85.     public function onSave$param )
  86.     {
  87.         try
  88.         {
  89.             TTransaction::open('dbarma'); // open a transaction
  90.             
  91.             /**
  92.             // Enable Debug logger for SQL operations inside the transaction
  93.             TTransaction::setLogger(new TLoggerSTD); // standard output
  94.             TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
  95.             **/
  96.             
  97.             $this->form->validate(); // validate form data
  98.             
  99.             $object = new Divulgacao;  // create an empty object
  100.             $data $this->form->getData(); // get form data as array
  101.             $object->fromArray( (array) $data); // load the object with data
  102.             $object->store(); // save the object
  103.             
  104.             // get the generated id
  105.             $data->id $object->id;
  106.             
  107.             $this->form->setData($data); // fill form data
  108.             TTransaction::close(); // close the transaction
  109.             if ($object instanceof Divulgacao)
  110.                 {
  111.                     $source_file   'tmp/'.$object->caminho_imagem;
  112.                     $target_file   'images/' $object->caminho_imagem;
  113.                     $finfo         = new finfo(FILEINFO_MIME_TYPE);
  114.                     
  115.                     // if the user uploaded a source file
  116.                     if (file_exists($source_file) AND ($finfo->file($source_file) == 'image/png' OR $finfo->file($source_file) == 'image/jpeg'))
  117.                     {
  118.                         // move to the target directory
  119.                         rename($source_file$target_file);
  120.                         try
  121.                         {
  122.                             TTransaction::open($this->database);
  123.                             // update the photo_path
  124.                             $object->caminho_imagem 'images/'.$object->caminho_imagem;
  125.                             $object->store();
  126.                             
  127.                             TTransaction::close();
  128.                         }
  129.                         catch (Exception $e// in case of exception
  130.                         {
  131.                             new TMessage('error'$e->getMessage());
  132.                             TTransaction::rollback();
  133.                         }
  134.                     }
  135.                     $image = new TImage($object->caminho_imagem);
  136.                     $image->style 'width: 100%';
  137.                     $this->frame->add$image );
  138.                 }            
  139.             
  140.             new TMessage('info'TAdiantiCoreTranslator::translate('Record saved'));
  141.         }
  142.         catch (Exception $e// in case of exception
  143.         {
  144.             new TMessage('error'$e->getMessage()); // shows the exception error message
  145.             $this->form->setData$this->form->getData() ); // keep form data
  146.             TTransaction::rollback(); // undo all pending operations
  147.         }
  148.     }
  149.     
  150.     /**
  151.      * Clear form data
  152.      * @param $param Request
  153.      */
  154.     public function onClear$param )
  155.     {
  156.         $this->form->clear(TRUE);
  157.     }
  158.     
  159.     /**
  160.      * Load object to form data
  161.      * @param $param Request
  162.      */
  163.     public function onEdit$param )
  164.     {
  165.         try
  166.         {
  167.             if (isset($param['key']))
  168.             {
  169.                 $key $param['key'];  // get the parameter $key
  170.                 TTransaction::open('dbarma'); // open a transaction
  171.                 $object = new Divulgacao($key); // instantiates the Active Record
  172.                 $this->form->setData($object); // fill the form
  173.                 TTransaction::close(); // close the transaction
  174.             }
  175.             else
  176.             {
  177.                 $this->form->clear(TRUE);
  178.             }
  179.             
  180.             if (isset($param['key']))
  181.             {
  182.             $key $param['key']; 
  183.             $object = new Divulgacao($key);
  184.             
  185.                 if ($object)
  186.                 {
  187.                     $image = new TImage($object->caminho_imagem);
  188.                     $image->style 'width: 100%';
  189.                     $this->frame->add$image );
  190.                 } 
  191.                 
  192.             }           
  193.             
  194.         }
  195.         catch (Exception $e// in case of exception
  196.         {
  197.             new TMessage('error'$e->getMessage()); // shows the exception error message
  198.             TTransaction::rollback(); // undo all pending operations
  199.         }
  200.     }
  201. }
  202. ?>

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (6)


NR

https://www.adianti.com.br/forum/pt/view_2315?erro-ao-gravar-imagem
SS

OK, Nataniel... vou ver esse parâmetro, mas isso explica por que a imagem não carrega para o componente após o upload, ou tem algo de errado no meu código?

Você chegou e ver a imagen do anexo?

NR

Sérgio, não analisei detalhadamente o restante do código. Mas sim, explica o não carregamento da imagem, pois um "Fatal Error" interrompe a execução do script.
SS

Pessoal, boa noite!

Habilitei a extensão e o erro mudou.

Uma coisa que percebi é que pediu usuario e senha na hora de carregar a imagem para o localhost. Coloquei a senha e usuario do computador mas não sei se é o correto.


Segue abaixo as mensagens de erro!


Erro
Arquivo não encontrado: '.ini'

Warning: rename(tmp/_DSC0443.jpg,images/_DSC0443.jpg): in C:xampphtdocsctrlarmasappcontrolDivulgacaoForm.class.php on line 132
SS

Mais um detalhe. A foto não carrega na imagem de jeito nenhum. Mesmo informando upload completo.
SS

Pessoal, estou encerrando esse post e abrindo outro. Os erros já corrigi. O problema apresentado agora é outro.