/**
  * @param  Application $app
  * @param  Request     $request
  * @return Response
  */
 public function fileUploadAction(Application $app, Request $request)
 {
     $uploadDir = __DIR__ . '/../../../web' . $app['config']['upload_dir'];
     $file = new File('file', new FileSystem($uploadDir));
     $file->addValidations(array(new Mimetype(array('image/png', 'image/gif', 'image/jpeg')), new Size('5M')));
     // Upload file to server
     try {
         $file->setName($app['slug']->slugify($file->getName()));
         $file->upload();
         $app['monolog']->addDebug(sprintf("File uploaded: %s", json_encode($file->getNameWithExtension())));
     } catch (\Exception $exception) {
         $errorMessage = join('<br />', $file->getErrors());
         $app['monolog']->addError(sprintf("Error during file upload: %s", $errorMessage));
         return new Response(sprintf("Erreur : %s", $errorMessage), 400);
     }
     // Save file to db
     try {
         $photo = $app['photos']->add($file->getNameWithExtension());
     } catch (\Exception $exception) {
         $app['monolog']->addError(sprintf("Error during file insertion: %s", $exception->getMessage()));
         // Remove file from upload dir
         unlink($uploadDir . $file->getNameWithExtension());
         return new Response(sprintf("Erreur : %s", $exception->getMessage()), 400);
     }
     // Generate thumbnails
     $app['photos']->generateThumbnails($photo);
     return new Response($photo->id);
 }
 /**
  * Upload
  * @param  \Upload\File $file The file object to upload
  * @return bool
  * @throws \RuntimeException   If overwrite is false and file already exists
  */
 public function upload(\Upload\File $file)
 {
     $newFile = $this->directory . $file->getNameWithExtension();
     if ($this->overwrite === false && file_exists($newFile)) {
         $file->addError('File already exists');
         throw new \Upload\Exception\UploadException('File already exists');
     }
     return $this->moveUploadedFile($file->getPathname(), $newFile);
 }
 /**
  * Validate
  * @param  \Upload\File $file
  * @return bool
  */
 public function validate(\Upload\File $file)
 {
     $fileExtension = strtolower($file->getExtension());
     $isValid = true;
     if (!in_array($fileExtension, $this->allowedExtensions)) {
         $this->setMessage(sprintf($this->message, implode(', ', $this->allowedExtensions)));
         $isValid = false;
     }
     return $isValid;
 }
 public function storeImage($article)
 {
     if (!is_dir($article->image_path)) {
         mkdir($article->image_path);
     }
     $storage = new FileSystem($article->image_path);
     $file = new File('file_upload', $storage);
     try {
         $file->upload();
     } catch (\Exception $e) {
         return ['success' => false, 'error' => $e->getMessage()];
     }
     return ['success' => true];
 }
Exemple #5
0
 /**
  * Validate
  * @param  \Upload\File $file
  * @return bool
  */
 public function validate(\Upload\File $file)
 {
     $fileSize = $file->getSize();
     $isValid = true;
     if ($fileSize < $this->minSize) {
         $this->setMessage('File size is too small');
         $isValid = false;
     }
     if ($fileSize > $this->maxSize) {
         $this->setMessage('File size is too large');
         $isValid = false;
     }
     return $isValid;
 }
 /**
  * Upload
  * @param  \Upload\File $file The file object to upload
  * @param  string $newName Give the file it a new name
  * @return bool
  * @throws \RuntimeException   If overwrite is false and file already exists
  */
 public function upload(\Upload\File $file, $newName = null)
 {
     if (is_string($newName)) {
         $fileName = strpos($newName, '.') ? $newName : $newName . '.' . $file->getExtension();
     } else {
         $fileName = $file->getNameWithExtension();
     }
     $newFile = $this->directory . $fileName;
     if ($this->overwrite === false && file_exists($newFile)) {
         $file->addError('File already exists');
         throw new \Upload\Exception\UploadException('File already exists');
     }
     return $this->moveUploadedFile($file->getPathname(), $newFile);
 }
 /**
  * @param array $params
  * @param array $files
  * @return array
  */
 public function run($params = array(), $files = array())
 {
     // Siga esse modelo para retornar erros
     $error = array("error" => false, "errorInfo" => "", "errorDesc" => "", "errorFields" => array());
     // Roda validação de campos simples
     foreach ($this->postRules as $field => $rule) {
         $data = array();
         $data[$field] = $rule;
         $validated = \GUMP::is_valid($params, $data);
         if ($validated !== true) {
             $error['errorFields'][] = $field;
         }
     }
     foreach ($this->fileRules as $field => $rule) {
         if (isset($files[$field]['name']) && !empty($files[$field]['name'])) {
             $storage = new FileSystem('public/uploads', BASEPATH);
             $file = new File($field, $storage);
             $file->setName(uniqid());
             $file->addValidations(array(new \Upload\Validation\Extension($rule['extension']), new \Upload\Validation\Size($rule['size'])));
             $name = $file->getNameWithExtension();
             try {
                 $file->upload();
                 $params[$field] = $name;
             } catch (\Exception $e) {
                 $error['errorFields'][] = $field;
             }
         } else {
             if (!isset($params[$field]) || empty($params[$field])) {
                 $error['errorFields'][] = $field;
             }
         }
     }
     if (!empty($error['errorFields'])) {
         $error['error'] = true;
         $error['errorInfo'] = "Erro ao salvar registro.";
         $error['errorDesc'] = "Preencha todos os campos corretamente";
         return array_merge_recursive($error, $params);
     } else {
         // Roda os tratamentos
         return $this->treatment($params, $files);
     }
 }
Exemple #8
0
 /**
  * Constructor
  *
  * @param int $maxSize Maximum acceptable file size in bytes (inclusive)
  * @param int $minSize Minimum acceptable file size in bytes (inclusive)
  */
 public function __construct($maxSize, $minSize = 0)
 {
     if (is_string($maxSize)) {
         $maxSize = \Upload\File::humanReadableToBytes($maxSize);
     }
     $this->maxSize = $maxSize;
     if (is_string($minSize)) {
         $minSize = \Upload\File::humanReadableToBytes($minSize);
     }
     $this->minSize = $minSize;
 }
Exemple #9
0
 /**
  * Constructor
  *
  * @param   Application  $application  The Application
  * @param   string       $key          The file's key in $_FILES superglobal
  *
  * @since   1.0
  */
 public function __construct(Application $application, $key = 'files')
 {
     $this->application = $application;
     $storage = new FileSystem(JPATH_THEMES . '/' . $this->application->get('system.upload_dir') . '/' . $this->application->getProject()->project_id);
     if (is_array($_FILES[$key])) {
         $_FILES[$key]['name'] = $_FILES[$key]['name'][0];
         $_FILES[$key]['error'] = $_FILES[$key]['error'][0];
         $_FILES[$key]['tmp_name'] = $_FILES[$key]['tmp_name'][0];
     }
     parent::__construct($key, $storage);
     $this->setValidations();
 }
 /**
  * Validate
  *
  * @param  \Upload\File $file
  *
  * @return bool
  */
 public function validate(\Upload\File $file)
 {
     return in_array($file->getMimetype(), $this->mimetypes);
 }
Exemple #11
0
 public function testParsesHumanFriendlyFileSizes()
 {
     $this->assertEquals(100, \Upload\File::humanReadableToBytes('100'));
     $this->assertEquals(102400, \Upload\File::humanReadableToBytes('100K'));
     $this->assertEquals(104857600, \Upload\File::humanReadableToBytes('100M'));
     $this->assertEquals(107374182400.0, \Upload\File::humanReadableToBytes('100G'));
     $this->assertEquals(100, \Upload\File::humanReadableToBytes('100F'));
     // <-- Unrecognized. Assume bytes.
 }
Exemple #12
0
 /**
  * Редактирование
  */
 public function anyEdit()
 {
     $id = (int) $this->getRequestParam('id') ?: null;
     $model = PlayerModel::find($id);
     $firstNameModel = $model->firstNameModel()->first();
     $lastNameModel = $model->lastNameModel()->first();
     if (empty($model)) {
         throw new HttpException(404, json_encode(['errorMessage' => 'Incorrect Player']));
     }
     if (Arr::get($this->getPostData(), 'submit') !== null) {
         $data = Arr::extract($this->getPostData(), ['slug', 'image', 'country', 'position', 'status', 'number', 'team', 'first_name', 'last_name', 'content']);
         // Транзакция для Записание данных в базу
         try {
             Capsule::connection()->transaction(function () use($data, $model, $firstNameModel, $lastNameModel) {
                 // Загрузка картинки
                 $file = new UploadFile('image', new FileSystem('uploads/images'));
                 // Optionally you can rename the file on upload
                 $file->setName(uniqid());
                 //                    // Validate file upload
                 //                    $file->addValidations(array(
                 //                        // Ensure file is of type image
                 //                        new UploadMimeType(['image/png','image/jpg','image/gif']),
                 //
                 //                        // Ensure file is no larger than 5M (use "B", "K", M", or "G")
                 //                        new UploadSize('50M')
                 //                    ));
                 // Try to upload file
                 try {
                     // Success!
                     $file->upload();
                     $image = '/' . static::IMAGE_PATH . '/' . $file->getNameWithExtension();
                 } catch (UploadException $e) {
                     // Fail!
                     $image = null;
                     Message::instance()->warning($file->getErrors());
                 } catch (Exception $e) {
                     // Fail!
                     $image = null;
                     Message::instance()->warning($file->getErrors());
                 }
                 $firstNameModel->updateOrCreate(['id' => $firstNameModel->id], ['text' => $data['first_name']]);
                 $lastNameModel->updateOrCreate(['id' => $lastNameModel->id], ['text' => $data['last_name']]);
                 foreach ($data['content'] as $iso => $d) {
                     $lang_id = Lang::instance()->getLang($iso)['id'];
                     EntityTranslationModel::updateOrCreate(['id' => $d['first_name_id']], ['text' => $d['first_name'], 'lang_id' => $lang_id, 'entity_id' => $firstNameModel->id]);
                     EntityTranslationModel::updateOrCreate(['id' => $d['last_name_id']], ['text' => $d['last_name'], 'lang_id' => $lang_id, 'entity_id' => $lastNameModel->id]);
                 }
                 Event::fire('Admin.entitiesUpdate');
                 // если нету нового изображения оставить прежний
                 if ($image) {
                     $imageId = PhotoModel::create(['path' => $image, 'is_bound' => 1])->id;
                     $model->update(['image_id' => $imageId]);
                 }
                 $model->update(['team_id' => $data['team'], 'slug' => $data['slug'], 'number' => $data['number'], 'status' => $data['status'], 'country_id' => $data['country'], 'position_id' => $data['position'], 'first_name_id' => $firstNameModel->id, 'last_name_id' => $lastNameModel->id]);
             });
             Message::instance()->success('Player was successfully saved');
         } catch (Exception $e) {
             Message::instance()->warning('Player was don\'t saved');
         }
     }
     $model = PlayerModel::find($id);
     $firstNameModel = $model->firstNameModel()->first();
     $lastNameModel = $model->lastNameModel()->first();
     // Загрузка контента для каждово языка
     $contents = [];
     foreach (Lang::instance()->getLangsExcept(Lang::DEFAULT_LANGUAGE) as $iso => $lang) {
         $contents[$iso]['firstName'] = $firstNameModel->translations()->whereLang_id($lang['id'])->first();
         $contents[$iso]['lastName'] = $lastNameModel->translations()->whereLang_id($lang['id'])->first();
     }
     //echo "<pre>";
     //print_r($contents);
     //die;
     $this->layout->content = View::make('back/players/edit')->with('item', $model)->with('contents', $contents);
 }
<?php

use Upload\Storage\FileSystem;
use Upload\File;
use Upload\Validation\Mimetype;
use Upload\Validation\Size;
$app->container->singleton('upload', function () {
    $storage = new FileSystem('uploads', $overwrite = true);
    $upload = new File('song', $storage);
    $upload->addValidations([new Mimetype('audio/mpeg'), new Size('10M')]);
    return $upload;
});
 /**
  * Main media upload API
  */
 protected function postMedia($mediaType = 'user', $item_id = 0)
 {
     // Get corresponding item
     switch ($mediaType) {
         case 'message':
             $item = Alert::find($item_id);
             $allowedTypes = array('alert_picture');
             break;
         case 'user':
             $item = User::find($item_id);
             $allowedTypes = array('profile_picture', 'cover_picture');
             break;
         case 'brand':
             $item = Brand::find($item_id);
             $allowedTypes = array('logo_picture', 'cover_picture');
             break;
         default:
             throw new Exception('Invalid media type:' . $mediaType);
             break;
     }
     if (!$item) {
         App::abort(404);
     }
     // Gathering and validate upload information
     $uploadFiles = Input::file();
     $uploadType = key($uploadFiles);
     if (!Input::hasFile($uploadType)) {
         array_shift($uploadFiles);
         $uploadType = key($uploadFiles);
     }
     if (!in_array($uploadType, $allowedTypes)) {
         return Redirect::back()->with('warning', 'Invalid upload name : ' . $uploadType);
     }
     // Early mime validation
     $validType = false;
     if ($mime = Input::file($uploadType)->getMimetype()) {
         $validType = strpos($mime, 'image') === 0;
     }
     if (!$validType) {
         return Redirect::back()->with('warning', 'Invalid mime type : ' . $mime);
     }
     // Prepare uploader
     $fs = new Filesystem();
     $storage = new UploadFileSystem($this->media_directory);
     $file = new UploadFile($uploadType, $storage);
     // Set to item's media slug
     $mediaName = $uploadType . '_' . $mediaType . '_' . $item->id;
     $file->setName($mediaName);
     // Validate file upload
     // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml
     $file->addValidations(array(new UploadMimetype($mime), new UploadSize('5M')));
     // Access data about the file that has been uploaded
     $data = array('path' => $this->media_directory . '/' . $file->getNameWithExtension(), 'name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions());
     // Try to upload file
     try {
         // If it already there, remove
         if ($fs->exists($data['path'])) {
             $fs->delete($data['path']);
         }
         $file->upload();
         chmod($data['path'], 0777);
         //why not 0644 or 0664
         $attachment = Attachment::create(array('mime' => $data['mime'], 'path' => $data['path'], 'url' => URL::to('/media/' . $mediaType . '/' . $uploadType . '/' . $item->id)));
         foreach ($item->attachments as $previousAttachment) {
             if ($previousAttachment->pivot->type == $uploadType) {
                 $item->attachments()->detach($previousAttachment->id);
             }
         }
         $item->attachments()->save($attachment, array('type' => $uploadType));
         return Redirect::back();
     } catch (Exception $e) {
         // Fail!
         $error = $file->getErrors();
         return Redirect::back()->with('warning', current($error));
     }
 }