upload image file and resized it.

@param \Illuminate\Http\Request $request

@return \Illuminate\Http\JsonResponse
769925
public function editVariation(Request $request)
    {
        $product = Product::findorfail($request->get('variation_id'));
        $view = view('avored-framework::product.variation-modal')
                            ->with('model', $product);

        return new JsonResponse(
            ['success' => true,
            'content' => $view->render(),
            'modalId' => '#variation-modal-' . $product->id]
        );
    }
920957
public function upload(HTTPRequest $request)
    {
        $assetAdmin = AssetAdmin::singleton();
        $uploadResponse = $assetAdmin->apiCreateFile($request);
        
        if ($uploadResponse->getStatusCode() == 200)
        {
            $responseData = Convert::json2array($uploadResponse->getBody());
            $responseData = array_shift($responseData);

            $record = $this->createDataObject($responseData['id']);

            $bulkToolsResponse = new HTTPBulkToolsResponse(false, $this->gridField);
            $bulkToolsResponse->addSuccessRecord($record);
            
            $responseData['bulkTools'] = json_decode($bulkToolsResponse->getBody());
            $uploadResponse->setBody(json_encode(array($responseData)));
        }

        return $uploadResponse;
    }
106115
public function xhrFileUploadAction(Request $request)
    {
        if (!$request->files->has('file')) {
            return new JsonResponse(
                array(
                    'error' => 400,
                    'error_message' => 'File to upload have to be under "file" key.',
                ),
                400
            );
        }
        try {
            return new JsonResponse(
                array('file' => $this->container->get('synapse.media.domain')
                    ->upload($request->files->get('file'))
                    ->normalize(),
                ),
                201
            );
        } catch (UnsupportedFileException $e) {
            return new JsonResponse(
                array(
                    'error' => 400,
                    'error_message' => 'File isnt supported by Synapse.',
                    'error_full_message' => $e->getMessage(),
                ),
                400
            );
        }
    }
1002934
public function addAction(Request $request)
    {
        $storage = new Storage();

        /* @var $form Form */
        $form = $this->createForm(new StorageForm(), $storage);

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($storage);
                $em->flush();

                return $this->redirect($this->generateUrl('storage_list'));
            }
        }

        return $this->render('AnimeDbCatalogBundle:Storage:add.html.twig', [
            'form' => $form->createView(),
            'guide' => $this->get('anime_db.api.client')->getSiteUrl(self::GUIDE_LINK),
        ]);
    }
918973
public function mediaAction(Request $request)
    {
        $query = $request->get('query');

        // TODO: meta search

        $results = [];
        foreach ($this->get('phlexible_media_manager.volume_manager')->all() as $volume) {
            $files = $volume->search($query);

            foreach ($files as $file) {
                /* @var $file ExtendedFileInterface */

                $results[] = [
                    'id' => $file->getId(),
                    'version' => $file->getVersion(),
                    'name' => $file->getName(),
                    'folder_id' => $file->getFolderId(),
                ];
            }
        }

        return new JsonResponse(['results' => $results]);
    }
1029309
public function ckeditorAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $funcNumber = $request->get('CKEditorFuncNum');

        if ($file = $request->files->get('upload')) {
            $supportedTypes = array(
                'image/jpeg',
                'image/png'
            );

            if ($file->getSize() > static::FILE_SIZE_MAX) {
                return $this->getCkeditorResponse(
                    'The uploaded file is too large. Please limit the file to under ' . (self::FILE_SIZE_MAX / 1024) . 'KiB',
                    '',
                    $funcNumber
                );
            }

            try {
                $uploadDir = $this->get('kernel')->getRootDir() . static::CKEDITOR_UPLOAD_DIR;
                $file      = File::createFromUploadedFile($file, $uploadDir);
                $file->moveUploadedFile();

                $em->persist($file);
                $em->flush();
            } catch (\Exception $e) {
                return $this->getCkeditorResponse($e->getMessage(), '', $funcNumber);
            }
        }

        if (!($file && file_exists($file->getPath()))) {
            return $this->getCkeditorResponse('There was an error while uploading the file. The file was not copied to the upload directory', '', $funcNumber);
        }

        $src = $this->generateUrl('file_view', array('id' => $file->getId()), true);

        return $this->getCkeditorResponse('Upload Successful', $src, $funcNumber);
    }
1184639
public function uploadFileAction(Request $request)
    {
        /** @var FormBuilderInterface $uploadForm */
        $form = $this->createForm(TranslationsFileUploadType::class);
        $configurator = $this->getAdminListConfigurator();

        if (Request::METHOD_POST === $request->getMethod()) {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $locales = $this->getParameter('kuma_translator.managed_locales');
                $data = $form->getData();
                $file = $data['file'];
                $force = $data['force'];
                $imported = $this->container->get('kunstmaan_translator.service.importer.importer')->importFromSpreadsheet($file, $locales, $force);
                $this->addFlash(FlashTypes::SUCCESS, sprintf('Translation imported: %d', $imported));
            }
        }

        return [
            'form' => $form->createView(),
            'adminlistconfigurator' => $configurator,
        ];
    }
671231
public function uploadAction()
    {
        $request = $this
            ->requestStack
            ->getCurrentRequest();

        /**
         * @var UploadedFile $file
         */
        $file = $request
            ->files
            ->get($this->uploadFieldName);

        if (!($file instanceof UploadedFile)) {
            return new JsonResponse([
                'status' => 'ko',
                'response' => [
                    'message' => 'Image not found',
                ],
            ]);
        }

        try {
            $image = $this
                ->imageUploader
                ->uploadImage($file);

            $routes = $this
                ->router
                ->getRouteCollection();

            $response = [
                'status' => 'ok',
                'response' => [
                    'id' => $image->getId(),
                    'extension' => $image->getExtension(),
                    'routes' => [
                        'view' => $routes
                            ->get($this->viewImageRouteName)
                            ->getPath(),
                        'resize' => $routes
                            ->get($this->resizeImageRouteName)
                            ->getPath(),
                    ],
                ],
            ];
        } catch (Exception $exception) {
            $response = [
                'status' => 'ko',
                'response' => [
                    'message' => $exception->getMessage(),
                ],
            ];
        }

        return new JsonResponse($response);
    }
177001
public function postImage()
	{
		$file = Input::file('file');
		$imageDir = Config::get('core::wardrobe.image_dir');
		$destinationPath = public_path(). "/{$imageDir}/";
		$filename = $file->getClientOriginalName();
		$resizeEnabled = Config::get('core::wardrobe.image_resize.enabled');
		
		if ($resizeEnabled)
		{
			$resizeWidth = Config::get('core::wardrobe.image_resize.width');
			$resizeHeight = Config::get('core::wardrobe.image_resize.height');
			$image = Image::make($file->getRealPath())->resize($resizeWidth, $resizeHeight, true);
			$image->save($destinationPath.$filename);
		}
		else
		{
			$file->move($destinationPath, $filename);
		}

		if (File::exists($destinationPath.$filename))
		{
			// @note - Using the absolute url so it loads images when ran in sub folder
			// this will make exporting less portable and may need to re-address at a later point.
			return Response::json(array('filename' => url("/{$imageDir}/".$filename)));
		}
		return Response::json(array('error' => 'Upload failed. Please ensure your public/img directory is writable.'));
	}
271472
public function run(Request $request) {
		$file = $request->files->get('file');

		try {
			// validate: upload progress
			if (!$file->isValid()) {
				throw new FileException($file->getErrorMessage());
			}

			// validate: mime type
			$mimeTypes = ['image/png', 'image/jpeg', 'image/jpg', 'video/mp4', 'video/quicktime'];
			if (!in_array($file->getClientMimeType(), $mimeTypes)) {
				throw new FileException('No matching mime type');
			}

			// validate: extension
			$exts = ['png', 'jpg', 'jpeg', 'mp4', 'mov'];
			if (!in_array($file->getClientOriginalExtension(), $exts)) {
				throw new FileException('No matching extension');
			}

			// move uploaded file
			$slugifier = new Slugify();
			$fileName = $file->getClientOriginalName();
			$fileName = str_replace('.' . $file->getClientOriginalExtension(), '', $fileName);
			$fileName = $slugifier->slugify($fileName) . '.' . $file->getClientOriginalExtension();
			$file->move($this->getModule()->getUploadPath()->toString(), $fileName);
			$payload = new Success([
				'filename' => $fileName,
				'url' => $this->getModule()->getUploadUrl() . '/' . urlencode($fileName)
			]);
		} catch (FileException $e) {
			$payload = new Failed(['error' => $e->getMessage()]);
		}

		return $this->responder->run($request, $payload);
	}
406374
public function cropImage(Request $request)
    {
        // check if user has permissions to access this link
        if(!User::hasAccess('Media', 'update')) {
            return $this->noPermission();
        }
        // get all inputs
        $inputs = $request->all();
        // Where is this file beeing croped
        $app = $inputs[4];

        // extension of the current image that is in crop process
        $mediaID = $inputs[0]['mediaID'];

        // check if user has permissions to access this link
        if(!User::hasAccess('Media', 'update', $mediaID, true)) {
            return $this->noPermission();
        }

        $media = Media::find($mediaID);
        // extension of the current image that is in crop process
        $extension = $inputs[0]['extension'];
        // destination folder
        $destinationPath = $inputs[0]['fileDirectory'];
        // width and heigth that appear in frontend
        $imageApperanceWidth = $inputs[2];
        $imageApperanceHeight = $inputs[3];
        // original image
        $url = strpos($inputs[0]['url'], '?');
        if($url == false) {
            $url = $inputs[0]['url'];
        }else{
            $url = explode('?', $inputs[0]['url'])[0];
        }
        $img = Image::make($url);
        // $croppedWidth = the width of the cropped window
        $croppedWidth = $inputs[1]['width'];
        // $newWidth = the new width calculated for the original dimensions of the image
        $newWidth = round($img->width() / ($imageApperanceWidth/$croppedWidth));

        // $croppedHeight = the height of the cropped window
        $croppedHeight = $inputs[1]['height'];
        // $newHeight = the new height calculated for the original dimensions of the image
        $newHeight = round($img->height() / ($imageApperanceHeight/$croppedHeight));

        // X and Y of the crop window
        $croppedX = $request->all()[1]['x'];
        $croppedY = $request->all()[1]['y'];
        // new X and Y calculated for the original dimensions of the image
        $newX = round(($img->width() / $imageApperanceWidth) * $croppedX);
        $newY = round(($img->height() / $imageApperanceHeight) * $croppedY);

        // crop image and save the new image
        $img->crop($newWidth, $newHeight, $newX, $newY);
        $img->save($url, 100);
        $media->touch();

        $media->deleteThumbs();
        $media->createDefaultThumbs(null, $app);

        return "OK";
    }
959547
public function filesAction(Request $request)
    {
        $id = $request->query->get('id');
        $em = $this->getDoctrine()->getManager();

        $files = $this->getDoctrine()->getRepository('ClasticMediaBundle:File')
            ->findBy(array(
                'directory' => $em->getReference('ClasticMediaBundle:Directory', $id),
            ));

        $data = array_map(function (File $file) {
            return array(
                'id' => $file->getId(),
                'text' => $file->getName(),
                'path' => '/uploads/documents/'.$file->getPath(),
            );
        }, $files);

        return new JsonResponse($data);
    }
530927
public function uploadAction(Request $request)
    {
        // @todo This method is insecure. Need to implement a CSFR check?

        global $kernel;

        $defaultUploadDir = realpath($kernel->getRootDir() . '/../web/uploads');
        $defaultUri       = '/uploads/';

        // Fire the pre-move event.
        $preMoveEvent = new UploadPreMoveEvent($request);
        $dispatcher   = $this->get('event_dispatcher');
        $dispatcher->dispatch('filefield.upload.pre_move', $preMoveEvent);

        $session = $this->get('session');
        $helper  = $this->get('filefield.upload_helper');

        $files     = $preMoveEvent->getFiles();
        $responses = [];
        foreach ($files as $formId => $file) {
            $ns        = 'filefield/' . $formId . '/';
            $uploadDir = $session->get($ns . 'uploadDir', $defaultUploadDir);
            $uri       = $session->get($ns . 'uri', $defaultUri);

            $response = null;
            if ($preMoveEvent->isDefaultMoveAllowed()) {
                if (empty($uploadDir) || empty($uri)) {
                    throw new \Exception('Missing uploadDir or uri.');
                }

                // Ensure upload directory exists.
                $fs = new Filesystem();
                if (!$fs->exists($uploadDir)) {
                    $fs->mkdir($uploadDir);
                }

                // @todo: Need to limit extension base on configuration.
                $ext     = strtolower($file->getClientOriginalExtension());
                $name    = basename(strtolower($file->getClientOriginalName()), $ext);
                $name    = $helper->getSaveName($name) . '.' . $ext;
                $size    = $helper->formatSize($file->getSize());
                $mime    = strtolower($file->getMimeType());
                $icon    = $helper->getFileIcon($mime);
                $iconUri = $helper->getIconUri() . $icon;

                // Move file(s) to permanent location.
                $file->move($uploadDir, $name);

                // Build a ajax response.
                $response = [
                    'name'     => $name,
                    'size'     => $size,
                    'mime'     => $mime,
                    'uri'      => $uri . $name,
                    'iconUri'  => $iconUri,
                    'template' => [
                        '.filefield-filename' => [
                            'text' => substr($name, 0, 40),
                            'attr' => [
                                'href' => $uri . $name,
                            ],
                        ],
                        '.filefield-filesize' => [
                            'text' => $size,
                        ],
                        '.filefield-fileicon' => [
                            'attr' => [
                                'src' => $iconUri,
                            ]
                        ],
                        '.filefield-value' => [
                            'val' => $uri . $name,
                        ]
                    ],
                ];
            }

            // Fire the move event.
            $moveEvent = new UploadMoveEvent($file, $uploadDir, $uri, $response);
            $dispatcher = $this->get('event_dispatcher');
            $dispatcher->dispatch('filefield.upload.move', $moveEvent);

            // Get the final file response.
            $response = $moveEvent->getResponse();

            if (empty($response) || !is_array($response)) {
                throw new \Exception('Invalid upload response.');
            }

            $responses[] = $response;
        }

        // Fire the post-move event.
        $postMoveEvent = new UploadPostMoveEvent($files, $responses);
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch('filefield.upload.post_move', $postMoveEvent);

        $response = new JsonResponse(['files' => $postMoveEvent->getResponse()]);
        if (!in_array('application/json', $request->getAcceptableContentTypes())) {
            $response->headers->set('Content-Type', 'text/plain');
        }

        return $response;
    }
1175076
public function postAction(Request $request)
    {
        $file = new File();
        $request = $this->requestManager->updateFileRequest($request);

        if ($formData = $request->get('metadata')) {
            $file = $this->restUtils->validateRequest($formData, $this->getModel());
        }

        /** @var FileModel $model */
        $model = $this->getModel();
        $file = $this->fileManager->handleSaveRequest($file, $request, $model);

        // Set status code and content
        $response = $this->getResponse();
        $response->setStatusCode(Response::HTTP_CREATED);
        $response->headers->set(
            'Location',
            $this->getRouter()->generate('gravitondyn.file.rest.file.get', array('id' => $file->getId()))
        );
        return $response;
    }
375597
public function upload(Request $request)
    {
        if ($request->hasFile('attachment')) {
            // config
            $config = config('sir-trevor-js');

            // file
            $file = $request->file('attachment');

            // Problem on some configurations
            $file = (!method_exists($file, 'getClientOriginalName')) ? $file['file'] : $file;

            // filename
            $filename = $file->getClientOriginalName();

            // suffixe if file exists
            $suffixe = '01';

            // verif if file exists
            while (file_exists(public_path($config['directory_upload']).'/'.$filename)) {
                $filename = $suffixe.'_'.$filename;

                ++$suffixe;

                if ($suffixe < 10) {
                    $suffixe = '0'.$suffixe;
                }
            }

            if ($file->move(public_path($config['directory_upload']), $filename)) {
                $return = [
                    'file' => [
                        'url' => '/'.$config['directory_upload'].'/'.$filename,
                    ],
                ];

                echo json_encode($return);
            }
        }
    }
689629
public function assignWatermark(Request $request)
    {
        $getWatermak = $this->getWatermak();

        if(!$getWatermak) {
            return $getWatermak;
        }

        // go through each select image
        foreach ($request->all() as $key => $file){
            $image = new Media($file);

            // check if user has permissions to access this link
            if(!User::hasAccess('Media', 'update', $image->mediaID, true)) {
                return $this->noPermission();
            }

            if ($image->type == "image") {

                // mark original image
                $url = strpos($image->url, '?');
                if($url == false) {
                    $url = base_path($image->url);
                }else{
                    $url = base_path(explode('?', $image->url)[0]);
                }

                // does file exist
                if(!File::exists($url)) {
                    throw new \Exception("Original images ".$url." doesn't exists.");
                }

                $originalImage = Image::make($url);

                // get width of the original image
                $originalWidth = (integer) $originalImage->width();

                // calculate a width for the watermark
                $width = round($originalWidth / 3);

                // get watermark
                $watermark = Image::make($getWatermak->url);

                // resize watermark
                $watermark->resize(
                    $width, null, function ($constraint) {
                        $constraint->aspectRatio();
                    }
                );
                $originalImage->insert($watermark, 'center');
                $originalImage->save($url, 100);

                $image->deleteThumbs();
                $image->createDefaultThumbs();

            }else{
                return "Some files could not be watermaked. Please select only image files.";
            }
        }
        return "OK";
    }
1215980
public function store(Request $request)
    {
        // check if user has permissions to access this link
        if(!User::hasAccess('Media', 'create')) {
            return $this->noPermission();
        }
        return (new Media())->upload($request);
    }