示例#1
0
 /**
  * @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);
 }
 /**
  * @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);
     }
 }
示例#3
0
<?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));
     }
 }