En este post el objetivo es conocer un poco más sobre este poderoso Framework y todas sus bondades, para ello en esta sección voy a compartir con ustedes como subir archivos al servidor y las validaciones respectivas (tamaño, tipo, extension, etc).
Primero como todos sabemos interactuamos con la vista para cargar el archivo a subir, en formato Akelos:
<p><label for=”screenshot_file”>_{Image}</label><br />
<?= $form_tag_helper->file_field_tag(‘screenshot[file]‘); ?> <i>_{Only accepts JPG, JPEG, PNG or GIF (no animation)}</i>
</p>
<p><label for=”screenshot_title”>_{Image description}</label><br />
<?php echo $active_record_helper->input(‘screenshot’, ‘title’,array(‘maxlength’=>50))?>
</p>
Luego interactúa el controlador primero guardando el nombre del archivo en BD y enviando los datos del archivo en un array a una función dentro del modelo, recojemos los valores POST:
@$fileuploaded = $this->params[‘screenshot’][‘file’];
@$this->params[‘screenshot’][‘file’] = $this->params[‘screenshot’][‘file’][‘name’];
Enviamos lo datos a la funció setUploadedFile:
$this->Screenshot->setUploadedFile($fileuploaded);
Seteamos la variable para realizar el save() en Akelos:
$this->Screenshot->setAttributes($this->params[‘screenshot’]);
Finalmente ahora el trabajo depende del modelo screenshot.php:
function setUploadedFile($var) {
$this->uploadedfile = $var;
}
Ahora validamos:
function validateOnCreate() {
if ($this->getErrorsOn(‘file’) === false) {
try{
$safe_extension = array(‘png’,’jpeg’,’jpg’,’gif’,’JPG’,’GIF’); // solo acepta estas extensiones (bueno para imagenes)
if ($this->uploadedfile[‘error’])
throw new Exception($this->t(‘Error while uploading file!’));
@$path_parts = pathinfo($this->uploadedfile[‘name’]);
if (!empty($path_parts[‘extension’])) {
if (!in_array($path_parts[‘extension’],$safe_extension))
throw new Exception($this->t(‘Invalid file type in pictures.’)); // validamos la extension del file
}
} catch (Exception $e) {
$this->addError(‘file’,'<span style=”color:red”>’.$e->getMessage().'</span>’);
}
}
if ($this->hasErrors()) return false;
else return true;
}
Ahora creamos una funcion para parsee el nombre del archivo y lo guarde en el campo file (por ejempo) de la BD:
function beforeCreate(){
@$path_parts = pathinfo($this->uploadedfile[‘name’]);
if (!empty($path_parts[‘basename’])) {
$name_length = 31 – strlen($path_parts[‘extension’]);
$this->uploadedfile[‘name’] = AK::randomString($name_length).’.’.$path_parts[‘extension’];
$this->set(‘file’, $this->uploadedfile[‘name’]);
}
return true;
}
Ahora usamos una función para guardar el file en nuestro servidor.
function afterCreate(){
$root = ‘ruta_path’;
$target_path_root = $root;
AK::make_dir(substr($target_path_root,0,-1)); // crea el directorio si no existe
$target_path = $target_path_root.basename($this->uploadedfile[‘name’]);
move_uploaded_file($this->uploadedfile[‘tmp_name’], $target_path); // lo copia
return true;
}
Y por últomo una función para elimianr en caso de hacer un destroy():
function beforeDestroy(){
$path = ‘ruta_path’;
@unlink($path.$this->get(‘file’));
return true;
}
Ojo: no cambiar el nombre de las funciones (son propias de Akelos), y si quiero actualizar mi imagen uso en vez de Create -> Update.
Espero que sea de ayuda para aquellos que quieren iniciarse con Akelos, luego explicaré como convertir una imagen a thumbnail.
Comments
cool… I love akelos so much,…
cool… I love akelos so much, in my office, i know people who composed AK framework as bermi team. 😀 contact Bermi about Bandung, he will tell you many thing :p