/** * Helper function in order to upload an image * in the future it will use imagine library for resizing * @param [laravel file] $file [the request file] * @return [array] status=>ok|error, fileName=>$name */ protected function uploadImageFile($file) { $extensions = ['png', 'jpeg', 'jpg', 'gif']; $maxSize = 1024 * 2000; // 200kb supposedly $path = public_path() . "/uploads/avatars"; $status = null; $fileName = null; $status = null; $ext = $file->guessClientExtension(); $size = $file->getClientSize(); $name = GUID::generate() . ".{$ext}"; if (in_array($ext, $extensions) and $size < $maxSize) { if ($file->move($path, $name)) { $status = 'ok'; } else { $status = 'error'; } } else { $status = 'error'; } return ['status' => $status, 'fileName' => $name]; }
define('ACTION_DEFAULT', 'view'); $actions = array(ACTION_DEFAULT, 'upload', 'delete', 'detail'); $action = isset($_REQUEST['action']) && in_array($_REQUEST['action'], $actions) ? $_REQUEST['action'] : ACTION_DEFAULT; switch ($action) { case 'upload': ob_start(); $_JSON = array(); if ($_FILES && isset($_FILES['file']['name'])) { foreach ($_FILES['file']['name'] as $key => $fileName) { try { $extsAllow = array('png', 'jpeg', 'jpg', 'gif'); $fileExt = mb_convert_case(pathinfo($fileName, PATHINFO_EXTENSION), MB_CASE_LOWER); if (!in_array($fileExt, $extsAllow)) { throw new \Exception(sprintf('Разрешены только файлы с расширениями %s.', '<b>' . implode($extsAllow, '</b>, <b>') . '</b>')); } $fileGuid = GUID::generate(); $fileNameNew = trim($fileGuid, '{}') . '.' . $fileExt; $fileSize = $_FILES['file']['size'][$key]; list($fileImageWidth, $fileImageHeight) = getimagesize($_FILES['file']['tmp_name'][$key]); // insert main data $stmt = DB::getConnection()->prepare("INSERT INTO `file` (file_guid, file_name, file_ext, file_original_name, file_size, file_image_width, file_image_height) VALUES (:file_guid, :file_name, :file_ext, :file_original_name, :file_size, :file_image_width, :file_image_height)"); $stmt->bindParam(':file_guid', $fileGuid); $stmt->bindParam(':file_name', $fileNameNew); $stmt->bindParam(':file_ext', $fileExt); $stmt->bindParam(':file_original_name', $fileName); $stmt->bindParam(':file_size', $fileSize); $stmt->bindParam(':file_image_width', $fileImageWidth); $stmt->bindParam(':file_image_height', $fileImageHeight); $stmt->execute(); $fileId = DB::getConnection()->lastInsertId(); // insert file content