Subir archivos en cakePHP

Para subir archivos en cakePHP debemos modificar la vista para que el formulario esté preparado para subir archivos:

<?php echo $this->Form->create('Country', array('type' => 'file')); ?>
 <fieldset>
 <legend><?php echo __('Add Country'); ?></legend>
 <?php
 echo $this->Form->input('country');
 echo $this->Form->file('archivo');
 echo $this->Form->input('last_update');
 ?>
 </fieldset>
<?php echo $this->Form->end(__('Submit')); ?>

Después en el controlador tenemos el archivo dentro de request->data, lo movemos igual que lo haríamos en php:

 public function add() {
 if ($this->request->is('post')) {
 $this->Country->create();
 if ($this->Country->save($this->request->data)) {
 $archivo = $this->request->data['Country']['archivo'];
 move_uploaded_file($archivo['tmp_name'], WWW_ROOT . 'files' . DS . $archivo['name']);
 $this->Flash->success(__('The country has been saved.'));
 return $this->redirect(array('action' => 'index'));
 } else {
 $this->Flash->error(__('The country could not be saved. Please, try again.'));
 }
 }
 }

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos