Exemple #1
0
 /**
  * Process upload image by AJAX 
  */
 public function uploadAction()
 {
     $module = $this->getModule();
     $config = Pi::user()->config('');
     $result = array('status' => false);
     $fakeId = $this->params('fake_id', 0);
     // Checking whether ID is empty
     if (empty($fakeId)) {
         $result['message'] = __('Invalid token!');
         return $result;
     }
     $rawInfo = $this->request->getFiles('upload');
     // Rename
     $ext = strtolower(pathinfo($rawInfo['name'], PATHINFO_EXTENSION));
     $rename = $fakeId . '.' . $ext;
     // Get path to store
     $location = $this->config('path_tmp') ?: sprintf('upload/%s/tmp', $this->getModule());
     //$destination = Pi::path($location);
     $uploadConfig = Pi::service('avatar')->getOption('upload');
     $extension = implode(',', $uploadConfig['extension']);
     $maxFile = $config['max_size'] ? $config['max_size'] * 1024 : 0;
     $maxSize = array();
     if ($config['max_avatar_width']) {
         $maxSize['width'] = (int) $config['max_avatar_width'];
     }
     if ($config['max_avatar_height']) {
         $maxSize['height'] = (int) $config['max_avatar_height'];
     }
     $upload = new UploadHandler();
     $upload->setDestination($location)->setRename($rename)->setExtension($extension);
     if ($maxFile) {
         $upload->setSize($maxFile);
     }
     if ($maxSize) {
         $upload->setImageSize($maxSize);
     }
     // Get raw file name
     if (empty($rawInfo)) {
         $content = $this->request->getContent();
         preg_match('/filename="(.+)"/', $content, $matches);
         $rawName = $matches[1];
     } else {
         $rawName = null;
     }
     // Checking whether uploaded file is valid
     if (!$upload->isValid($rawName)) {
         $result['message'] = implode(', ', $upload->getMessages());
         return $result;
     }
     $upload->receive();
     //$fileName = $upload->getDestination() . '/' . $rename;
     $fileName = $location . '/' . $upload->getUploaded();
     // Resolve allowed image extension
     $imageSize = array();
     $imageSizeRaw = getimagesize(Pi::path($fileName));
     $imageSize['w'] = $imageSizeRaw[0];
     $imageSize['h'] = $imageSizeRaw[1];
     $uploadInfo = array('tmp_name' => $fileName, 'w' => $imageSize['w'], 'h' => $imageSize['h']);
     // Save info to session
     $session = $this->getUploadSession($module, 'avatar');
     $session->{$fakeId} = $uploadInfo;
     // Prepare return data
     $result['data'] = array_merge(array('originalName' => $rawInfo['name'], 'size' => $rawInfo['size'], 'preview_url' => Pi::url($fileName), 'basename' => basename($fileName), 'type' => $ext, 'id' => $fakeId, 'filename' => $fileName), $imageSize);
     $result['status'] = true;
     //return $result; for ie10+ bug
     Pi::service('log')->mute();
     echo json_encode($result);
     exit;
 }