จาก Form ด้านบนจะเปลี่ยนเป็นอัพไฟล์รูปภาพพร้อมกับย่อขนาดไฟล์
การย่อไฟล์จะใช้ class.upload.php ตามไฟล์แนบนี้ โดยเอาไปไว้ในโฟลเดอร์ helpers ตัวอย่างโค้ดใน Model
โค้ด: เลือกทั้งหมด
protected $msg = '';
function getMsg() {
return $this->msg;
}
function uploadFile() {
$path_upload = JPATH_COMPONENT_ADMINISTRATOR.DS.'files_upload'.DS;
$type_file = JFile::getExt($_FILES['file_upload']['name']);
$real_name = JFile::getName($_FILES['file_upload']['name']);
$file_name = md5($real_name.time()).'.'.$type_file;
if(!preg_match("[^image+.]", $_FILES['file_upload']['type'])) {
$this->msg = 'Error : Support image file';
return false;
}
if(JFile::copy($_FILES['file_upload']['tmp_name'], $path_upload.$file_name)) {
$file_name = $this->ResizePicture($file_name, $path_upload); // ทำงาน function ย่อรูปภาพ
$db = JFactory::getDbo();
$query = 'INSERT INTO '.$db->nameQuote('#__upload_file').' SET '
.$db->nameQuote('real_name').'='.$db->quote($real_name).', '
.$db->nameQuote('file_name').'='.$db->quote($file_name).', '
.$db->nameQuote('type').'='.$db->quote($type_file).', '
.$db->nameQuote('create_date').'='.$db->quote(time());
$db->setQuery($query);
$db->query();
$id = $db->insertid();
if($id != '') {
return true;
}
}
return false;
}
function ResizePicture($file, $path) {
require_once JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'class.upload.php';
$handle = new upload($path.$file);
if ($handle->uploaded) {
$handle->image_resize = true;
$handle->image_x = 120;
$handle->image_y = 120;
$handle->image_ratio = true;
$handle->image_ratio_no_zoom_in = true;
$handle->file_auto_rename = false;
$handle->file_overwrite = true;
$handle->Process($path);
if ($handle->processed) {
$this->msg = 'image resized';
} else {
$this->msg = 'error : ' . $handle->error;
}
}
return $handle->file_dst_name;
}