Upload and save image information

@param UploadImageRequest $request
@return \Illuminate\Http\JsonResponse
@throws \Exceptioni
@throws \Throwable
439467
public function store(UploadImageRequest $request)
    {
        $upload = $this->uploader->upload($request->file('image'), storage_path('app/laramanager/images'));

        return $this->imageRepository->create($upload->toArray());
    }
8647
public function upload(FileRequest $request)
    {
        $crudeName = $request->input('crudeName');
        $crude = CrudeInstance::get($crudeName);
        $files = $request->file()['file'];
        $id = $request->input('modelId');
        $errors = [];

        if ($crude instanceof \JanDolata\CrudeCRUD\Engine\Interfaces\WithValidationInterface) {
            foreach($files as $key => $file) {
                $rules = $crude->getValidationRules(['file']);

                $mime = $file->getMimeType();
                $fileTypeRules = 'file_'.collect(explode('/', $mime))->first();

                empty($crude->getValidationRules([$fileTypeRules])[$fileTypeRules])
                    ? $rules = $rules
                    : $rules['file'] = $rules['file'] . '|' . $crude->getValidationRules([$fileTypeRules])[$fileTypeRules];

                $validator = Validator::make(['file' => $file], $rules);

                if ($validator->fails()) {
                    unset($files[$key]);
                    $errors[] = $file->getClientOriginalName() . ': '. $validator->messages()->first();
                }
            }
        }

        $model = empty($files)
            ? $crude->getById($id)
            : $crude->uploadFilesById($id, $files);

        $response = ['success' => true, 'model' => $model];

        if (!empty($errors)) {
            $response = array_merge($response, ['errors' => join('<br/>', $errors)]);
            $response['success'] = false;
        }

        return $response;
    }
475050
public function uploadAction(Request $request)
	{
		$postRequest = $request->request;
		$files = $request->files;

		if (!$files->has('file') || !$files->get('file') instanceof UploadedFile || !$files->get('file')->isValid()) {
			$message = 'Error uploading the file';

			throw new CmsException(null, $message);
		}

		$file = $files->get('file');
		/* @var $file UploadedFile */

		$em = $this->container->getDoctrine()->getManager();

		$em->beginTransaction();

		$repository = $em->getRepository(FileAbstraction::CN());
		/* @var $repository FileNestedSetRepository */

		$repository->getNestedSetRepository()->lock();

		// Permission check
		$uploadPermissionCheckFolder = null;

		if ($postRequest->get('folder')) {
			$uploadPermissionCheckFolder = $this->getFolder('folder');
		} else {
			$uploadPermissionCheckFolder = new SlashFolder();
		}

		$this->checkActionPermission($uploadPermissionCheckFolder, FileAbstraction::PERMISSION_UPLOAD_NAME);

		try {
			// getting the folder to upload in
			$folder = null;
			if ($postRequest->get('folder')) {
				$folder = $this->getFolder('folder');
			}

			// Will return the top folder created/found from folderPath string
			$firstSubFolder = null;

			// Create/get folder by path provided
			$folderPath = $postRequest->get('folderPath', '');

			$folderPath = trim(str_replace('\\', '/', $folderPath), '/');

			if ( ! empty($folderPath)) {
				$folderPathParts = explode('/', $folderPath);
				foreach ($folderPathParts as $part) {

					$folderFound = false;
					$children = null;

					if ($folder instanceof Folder) {
						$children = $folder->getChildren();
					} elseif (is_null($folder)) {
						$children = $repository->getRootNodes();
					} else {
						throw new \LogicException("Not supported folder type: " . gettype($folder) . ', class: ' . get_class($folder));
					}

					foreach ($children as $child) {
						if ($child instanceof Folder) {
							$_name = $child->getTitle();
							if (strcasecmp($_name, $part) === 0) {
								$folderFound = $child;
								break;
							}
						}
					}

					if ($folderFound) {
						$folder = $folderFound;
					} else {
						$folder = $this->createFolder($part, $folder);
					}

					if (empty($firstSubFolder)) {
						$firstSubFolder = $folder;
					}
				}
			}

			// checking for replace action
			if ($postRequest->has('file_id')) {
				$fileToReplace = $this->getFile('file_id');
				$this->getFileStorage()->replaceFile($fileToReplace, $file);

				// close transaction and unlock the nested set
				$em->commit();
				$repository->getNestedSetRepository()->unlock();

				return new SupraJsonResponse($this->imageAndFileOutput($fileToReplace));
			}

			$fileEntity = null;

			if ($this->getFileStorage()->isSupportedImageFormat($file->getPathname())) {
				$fileEntity = new Image();
			} else {
				$fileEntity = new File();
			}
			$em->persist($fileEntity);

			$fileEntity->setFileName($file->getClientOriginalName());
			$fileEntity->setSize($file->getSize());
			$fileEntity->setMimeType($file->getMimeType());

			// additional jobs for images
			if ($fileEntity instanceof Image) {
				// store original size
				$imageProcessor = $this->getFileStorage()->getImageResizer();
				$imageInfo = $imageProcessor->getImageInfo($file->getPathname());
				$fileEntity->setWidth($imageInfo->getWidth());
				$fileEntity->setHeight($imageInfo->getHeight());
			}

			if ( ! empty($folder)) {
				// get parent folder private/public status
				$publicStatus = $folder->isPublic();
				$fileEntity->setPublic($publicStatus);

				// Flush before nested set UPDATE
				$em->flush();

				$folder->addChild($fileEntity);
			}

			// when "force" set to true, then we need to ignore duplicate
			// filename exception, so postfix will be added to filename
			if ($fileEntity instanceof File) {
				if ($postRequest->has('force') && $postRequest->filter('force', null, false, FILTER_VALIDATE_BOOLEAN)) {
					try {
						$this->getFileStorage()->validateFileUpload($fileEntity, $file['tmp_name']);
					} catch (DuplicateFileNameException $e) {

						$siblings = $fileEntity->getSiblings();

						$existingNames = array();
						foreach($siblings as $siblingEntity) {
							if ( ! $siblingEntity->equals($fileEntity)) {
								$existingNames[] = $siblingEntity->getFileName();
							}
						}

						$extension = $fileEntity->getExtension();
						$fileNamePart = $fileEntity->getFileNameWithoutExtension();

						$possibleName = null;
						// assume that 1000 iterations is enough, to create unique name
						// if not, well... duplicate file name exception will be thrown
						for ($i = 1; $i < 1000; $i++) {
							$possibleName = sprintf(self::DUPLICATE_NAME_PATTERN, $fileNamePart, $i, $extension);

							if ( ! in_array($possibleName, $existingNames)) {
								$fileEntity->setFileName($possibleName);
								break;
							}
						}
					}
				}
			}

			// when it is not enough available memory to complete Image resize/crop
			// file will be uploaded as simple File entity
			if ($fileEntity instanceof Image) {
				try {
					$this->getFileStorage()->validateFileUpload($fileEntity, $file->getPathname());
				} catch (InsufficientSystemResources $e) {

					// Removing image
					$em->remove($fileEntity);
					$em->flush();

					$fileEntity = new File();

					$em->persist($fileEntity);

					$fileEntity->setFileName($file->getClientOriginalName());
					$fileEntity->setSize($file->getSize());
					$fileEntity->setMimeType($file->getType());

					if ( ! is_null($folder)) {
						$publicStatus = $folder->isPublic();
						$fileEntity->setPublic($publicStatus);

						// Flush before nested set UPDATE
						$em->flush();

						$folder->addChild($fileEntity);
					}

					$message = "Amount of memory required for image [{$file['name']}] resizing exceeds available, it will be uploaded as a document";

					$responseWarning = $message;
				}
			}

			$em->flush();

			// trying to upload file
			$this->getFileStorage()->storeFileData($fileEntity, $file->getPathname());
		} catch (\Exception $e) {

			try {
				// close transaction and unlock the nested set
				$em->flush();
				$em->rollback();
				$repository->getNestedSetRepository()->unlock();
			} catch (\Exception $e) {
				$this->container->getLogger()->error("Failure on rollback/unlock: ".$e->__toString());
			}

			throw new CmsException(null, $e->getMessage(), $e);
		}

		// close transaction and unlock the nested set
		$em->commit();
		$repository->getNestedSetRepository()->unlock();

		// generating output
		$output = $this->imageAndFileOutput($fileEntity);

		if ( ! empty($firstSubFolder)) {
			$firstSubFolderOutput = $this->entityToArray($firstSubFolder);
			$output['folder'] = $firstSubFolderOutput;
		}

		$response = new SupraJsonResponse();

		$response->setData($output);

		if (isset($responseWarning)) {
			$response->setWarningMessage($responseWarning);
		}

		return $response;
	}
1173439
public function uploadAction(Request $request)
    {
        $manager = $this->getDoctrine()->getManager();

        $file = $request->files->get('file');

        $new = new File();
        $new->setFile($file);
        $new->setMimeType($file->getMimeType());
        $new->setName($file->getClientOriginalName());
        $new->setSize($file->getClientSize());
        $new->setOwned(false);

        $manager->persist($new);
        $manager->flush();

        return new Response($new->getId(), 200);
    }
352859
public function save_file(Request $request)
    {
        $filepath = $request->input('filepath');
        $filedata = $request->input('filedata');
        $data = file_put_contents(base_path($filepath), $filedata);
        return response()->json(['success' => true]);
    }
1011395
public function uploadFilesWysiwygAction(Request $request)
    {
        $template = 'AlpixelMediaBundle:admin:blocks/upload_wysiwyg.html.twig';

        try {
            $file = $request->files->get("upload");
            if ($file !== null) {
                $media = $this->get('alpixel_media.manager')->upload($file, $request->get('folder'), null);

                return $this->render(
                    $template,
                    [
                        'file_uploaded' => $media,
                    ]
                );
            } else {
                if (empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower(
                        $_SERVER['REQUEST_METHOD']
                    ) == 'post'
                ) {
                    throw new UploadException(
                        sprintf("Votre fichier dépasse la limite maximale de %s", ini_get('post_max_size'))
                    );
                }
            }
        } catch (\Exception $e) {
            return $this->render(
                $template,
                [
                    'error' => $e->getMessage(),
                ]
            );
        }
    }
501658
public function indexAction(Request $request)
    {
        $fileEntity = new UploadFile();

        $form = $this->createForm(UploadFileType::class, $fileEntity, [
            'method' => 'POST',
        ]);

        $form->handleRequest($request);

        if ($form->isValid()) {
            /* @noinspection PhpUndefinedMethodInspection */
            if (!$fileEntity->getFile()->getError()) {
                $fileEntity->move($this->getParameter('kernel.root_dir') . '/../' . $this->getParameter('compo_import.upload_dir'));

                $this->getDoctrine()->getManager()->persist($fileEntity);
                $this->getDoctrine()->getManager()->flush();

                $this->runCommand($fileEntity);

                $this->getDoctrine()->getManager()->persist($fileEntity);
                $this->getDoctrine()->getManager()->flush();

                return $this->redirect($this->admin->generateUrl('upload', [
                    'import_id' => $fileEntity->getId(),
                ]));
            }

            /* @noinspection PhpUndefinedMethodInspection */
            $form->get('file')->addError(new FormError($fileEntity->getFile()->getErrorMessage()));
        }

        /** @var AbstractAdmin $admin */
        $admin = $this->get('sonata.admin.pool')->getInstance($this->admin->getCode());

        $builder = $admin->getExportFields();

        return $this->renderWithExtraParams('@CompoImport/Default/index.html.twig', [
            'form' => $form->createView(),
            'base_template' => $this->getBaseTemplate(),
            'builder' => $builder,
            'action' => 'import',
            'letters' => $this->getLetterArray(),
        ]);
    }
1058293
public function uploadAction(Request $request)
    {
        $media = $this->get('opifer.media.media_manager')->createMedia();
        $em = $this->getDoctrine()->getManager();

        foreach ($request->files->all() as $files) {
            if ((!is_array($files)) && (!$files instanceof \Traversable)) {
                $files = [$files];
            }

            foreach ($files as $file) {
                $media = clone $media;
                $media->setFile($file);

                if (strpos($file->getClientMimeType(), 'image') !== false) {
                    $media->setProvider('image');
                } else {
                    $media->setProvider('file');
                }

                $em->persist($media);
            }
        }
        $em->flush();

        $media = $this->get('jms_serializer')->serialize($media, 'json');

        return new Response($media, 200, ['Content-Type' => 'application/json']);
    }
21025
public function getSaveValue(Request $request)
    {
        $parameters = $this->parseFieldParameters();

        return (new Uploader)->uploadFile($request->file($this->getPrefixedFieldName()), isset($parameters['intervention']) ? $parameters['intervention'] : [], isset($parameters['upload_sub_dir']) ? $parameters['upload_sub_dir'] : null);
    }
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;
    }
1296573
public function postAddPhotos(Request $request)
    {
        if (!$request->hasFile('photos')) {
            return response('', 400);
        }

        foreach ($request->file('photos') as $file) {
            $photo = Photo::upload($file->getRealPath());

            session()->push('photos', [
                'photo_id' => $photo->getKey(),
                'filename' => $file->getClientOriginalName(),
            ]);
        }
    }
7424
public function upload(Request $request)
    {
        $validation = app(ValidationService::class)->check([
            'location' => ['required'],
        ]);

        if (!$validation['errors']) {
            $file = $request->file('location');
            $fileSaved = app(FileService::class)->saveFile($file, 'public/images', [], true);
            $fileSaved['name'] = CryptoService::encrypt($fileSaved['name']);
            $fileSaved['mime'] = $file->getClientMimeType();
            $fileSaved['size'] = $file->getClientSize();
            $response = app(CmsResponseService::class)->apiResponse('success', $fileSaved);
        } else {
            $response = app(CmsResponseService::class)->apiErrorResponse($validation['errors'], $validation['inputs']);
        }

        return $response;
    }
1147475
public function store(Create $request)
    {
        $data = $request->all();

        unset($data['image']);

        if (\Input::hasFile('image')) {
            // upload image
            $this->uploader->upload('image')->save('images/articles');

            $data['image'] = $this->uploader->getFilename();
        }

        $data['user_id'] = \Auth::id();
        $data['slug'] = Str::slug($data['title']);

        $this->repository->create($data);

        return $this->redirect(isOnPages() ? 'pages.index' : 'articles.index');
    }
1154036
public function post(Request $request)
	{
		$this->validate($request, [
            'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
        ]);

		$fileName = basename($request->file->getClientOriginalName(), '.' . $request->file->getClientOriginalExtension());
		$fileExtension = $request->file->getClientOriginalExtension();
		$postName = $this->sanitizeUrl($fileName);
		$mime = $request->file->getMimeType();

		$postmeta = NikuPostmeta::where([
			['meta_key', '=', 'attachment_url'],
			['meta_value', 'LIKE', '/uploads/images/' . $fileName . '%']
		])->get();

		if($postmeta->count() != 0){
			$count = $postmeta->count() + 1;
			$fileCount = '-' . $count;
		} else {
			$fileCount = '';
		}

		$postName = $postName . $fileCount;
		$fileName = $fileName . $fileCount . '.' . $fileExtension;

		$post = new NikuPosts;
		$post->post_title = $fileName;
		$post->post_name = $postName;
		$post->post_type = 'attachment';
		$post->post_mime_type = $mime;
		$post->status = 'inherit';
		if(Auth::check()){
			$post->post_author = Auth::user()->id;
		} else {
			$post->post_author = '0';
		}
		$post->save();

		$postmeta = new NikuPostmeta;
		$postmeta->post_id = $post->id;
		$postmeta->meta_key = 'attachment_url';
		$postmeta->meta_value = '/uploads/images/' . $fileName;
		$postmeta->save();

        $request->file->move(public_path('uploads/images'), $fileName);

        $postObject = collect([
        	'status' => 0,
        	'postmeta' => [
        		0 => [
        			'meta_value' => $postmeta->meta_value,
        		]
        	],
        	'id' => $postmeta->post_id
        ]);

        return response()->json([
		    'object' => $postObject
		]);
	}
1371930
public function submitAction(Request $request)
    {
        try {
            $manager = $this->get('ongr_settings.settings_manager');
            $data = $request->get('setting');

            if (!empty($data['value']) && !is_string($data['value'])) {
                $data['value'] = json_encode($data['value']);
            }

            if ($request->get('force')) {
                $name = $request->get('name');
                $manager->update($name, $data);
            } else {
                $manager->create($data);
            }

            return new JsonResponse(['error' => false]);
        } catch (\Exception $e) {
            return new JsonResponse(
                [
                    'error' => true,
                    'message' => 'Error occurred! Something is wrong with provided data. '.
                        'Please try to submit form again.'
                ]
            );
        }
    }
977566
public function store(UploadFileRequest $request)
    {
        $file = $request->file('file');

        $fileName  = uniqid('upload') . '.' . $file->extension();
        $storeDir  = rtrim(config('cms-upload-module.upload.path'), '/');
        $storePath = $storeDir . '/' . $fileName;

        $mimeType = $file->getMimeType();

        if ( ! $this->fileChecker->check($file->getClientOriginalName(), $mimeType)) {
            return response()->json([
                'success' => false,
                'error'   => cms_trans('upload.error.disallowed-type'),
            ]);
        }

        // Apply custom request-specified validation
        $rules     = $request->getNormalizedValidationRules();
        $validator = $this->getCustomValidator($file, $rules);

        if ($validator) {
            try {
                if ($validator->fails()) {
                    return response()->json([
                        'success' => false,
                        'error'   => implode("\n", array_get($validator->getMessageBag()->toArray(), 'file', [])),
                    ]);
                }
            } catch (Exception $e) {
                cms()->log('error', "Error applying validation custom rules for uploaded file", [
                    'file'  => $storePath,
                    'rules' => $rules,
                ]);
                return response()->json([
                    'success' => false,
                    'error'   => cms_trans('upload.error.validation-failed'),
                ]);
            }
        }

        $path = $file->move($storeDir, $fileName);

        if (false === $path || ! $this->files->exists($storePath)) {
            // @codeCoverageIgnoreStart
            cms()->log('error', "Error moving uploaded file to {$storePath}");
            return response()->json([
                'success' => false,
                'error'   => cms_trans('upload.error.upload-failed'),
            ]);
            // @codeCoverageIgnoreEnd
        }

        $data = [
            'reference' => $request->input('reference'),
            'name'      => $request->input('name'),
            'uploader'  => $this->core->auth()->user()->getUsername(),
            'file_size' => $this->files->exists($path) ? $this->files->size($path) : null,
        ];

        if ( ! ($record = $this->fileRepository->create($path, $data))) {
            // @codeCoverageIgnoreStart
            cms()->log('error', "Error saving record for uploaded file at {$storePath}");
            return response()->json([
                'success' => false,
                'error'   => cms_trans('upload.error.saving-record-failed'),
            ]);
            // @codeCoverageIgnoreEnd
        }

        if ($this->sessionGuard->enabled()) {
            $this->sessionGuard->link($record->getKey());
        }

        $this->performGarbageCollection();

        return response()->json([
            'success'   => true,
            'id'        => $record->getKey(),
            'reference' => $record->reference,
            'name'      => $record->name,
            'size'      => $record->file_size,
            'mimetype'  => $mimeType,
        ]);
    }
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);
            }
        }
    }