Upload File.

@param Request $request

@return ResultResponse
@Route("", name="mediamanager_upload")
423630
public function uploadAction(Request $request)
    {
        $folderId = $request->get('folder_id', null);

        try {
            $volumeManager = $this->get('phlexible_media_manager.volume_manager');
            $volume = $volumeManager->getByFolderId($folderId);
            $folder = $volume->findFolder($folderId);

            if (empty($folder)) {
                return new ResultResponse(
                    false,
                    'Target folder not found.',
                    [
                        'params' => $request->request->all(),
                        'files' => $request->files->all(),
                    ]
                );
            }

            if (!$request->files->count()) {
                return new ResultResponse(
                    false,
                    'No files received.',
                    [
                        'params' => $request->request->all(),
                        'files' => $request->files->all(),
                    ]
                );
            }

            $uploadHandler = $this->get('phlexible_media_manager.upload.handler');

            $cnt = 0;
            foreach ($request->files->all() as $uploadedFile) {
                /* @var $uploadedFile UploadedFile */

                $file = $uploadHandler->handle($uploadedFile, $folderId, $this->getUser()->getId());

                if ($file) {
                    ++$cnt;

                    $body = 'Filename: '.$uploadedFile->getClientOriginalName().PHP_EOL
                        .'Folder:   '.$folder->getName().PHP_EOL
                        .'Filesize: '.$file->getSize().PHP_EOL
                        .'Filetype: '.$file->getMimeType().PHP_EOL;

                    $message = MediaManagerMessage::create('File "'.$file->getName().'" uploaded.', $body);
                    $this->get('phlexible_message.message_poster')->post($message);
                }
            }

            return new ResultResponse(
                true,
                $cnt.' file(s) uploaded.',
                [
                    'params' => $request->request->all(),
                    'files' => $request->files->all(),
                ]
            );
        } catch (\Exception $e) {
            return new ResultResponse(
                false,
                $e->getMessage(),
                [
                    'params' => $request->request->all(),
                    'files' => $request->files->all(),
                    'trace' => $e->getTraceAsString(),
                    'traceArray' => $e->getTrace(),
                ]
            );
        }
    }
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;
    }
581245
public function createDirectory(Request $request)
    {
        $this->authorize(MediasPolicy::PERMISSION_CREATE);

        // TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
        $validator = validator($data = $request->all(), [
            'name'     => ['required', 'string'], // TODO: check if the folder does not exists
            'location' => ['required', 'string'],
        ]);

        if ($validator->fails()) {
            return $this->jsonResponseError([
                'messages' => $validator->messages(),
            ], 422);
        }

        $this->media->makeDirectory(
            $path = trim($data['location'], '/').'/'.Str::slug($data['name'])
        );

        return $this->jsonResponseSuccess(['data' => compact('path')]);
    }
509499
public function searchMediaAction(Request $request)
    {
        $response = $this->getFilter($request);
        if ($response['success'] === false) {
            return $response['value'];
        }
        $filter = $response['crypted'];

        $mm = $this->getMediaManager();

        $q = ($request->query->has('q')) ? $request->query->get('q') : null;
        $type = ($request->query->has('type')) ? $request->query->get('type') : null;

        $medias = $mm->search($filter, $q, $type);

        return $this->createResponse($medias);
    }
1097265
public function rename(Request $request)
    {
        $path = $request->get('path');
        $original = $request->get('original');
        $newName = $request->get('newName');
        $type = $request->get('type');

        try {
            $result = $this->mediaManager->rename($path, $original, $newName);

            if ($result !== true) {
                $error = $this->mediaManager->errors() ?: trans('media-manager::messages.rename_error', ['entity' => $type]);

                return $this->errorResponse($error);
            }

            return ['success' => trans('media-manager::messages.rename_success', ['entity' => $type])];
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }
1046942
public function upload(Request $request)
    {
        $interventionConfig = json_decode($request->input('intervention'), true);
        $appendedPath = $request->input('uploadSubDir');

        $uploadResponse = (new Uploader)->fancyUpload($request, $interventionConfig ?: [], $appendedPath);

        return response()->json($uploadResponse);
    }
116242
public function upload(Request $request)
    {
        $attachment = [];
        foreach ($request->allFiles() as $files) {
            $files = Arr::wrap($files);

            foreach ($files as $file) {
                $attachment[] = $this->createModel($file, $request);
            }
        }

        $attachment = count($attachment) > 1 ? $attachment : reset($attachment);

        return response()->json($attachment);
    }
759009
public function downloadAction(Request $request)
    {
        /**
         * @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media
         * @var \League\Flysystem\File $file
         */
        list($media, $file) = $this->findMedia($request->attributes->get('key'));

        $lastModified = $media->getUpdatedAt();

        $response = new Response();
        $response->setPublic();
        $response->setLastModified($lastModified);
        $response->setEtag(md5($file->getPath().$lastModified->getTimestamp()));
        if ($response->isNotModified($request)) {
            return $response;
        }

        $response = new StreamedResponse();
        $response->setPublic();
        $response->setLastModified($lastModified);
        $response->setEtag(md5($file->getPath().$lastModified->getTimestamp()));

        // Set the headers
        $response->headers->set('Content-Type', $file->getMimetype());
        $response->headers->set('Content-Length', $file->getSize());

        $response->setCallback(function () use ($file) {
            fpassthru($file->readStream());
        });

        return $response;
    }
1252556
public function mediaAction(Request $request)
    {
        $fileId = $request->get('file_id');
        $fileVersion = $request->get('file_version');
        $templateKey = $request->get('template_key');

        $cacheManager = $this->get('phlexible_media_cache.cache_manager');
        $storageManager = $this->get('phlexible_media_cache.storage_manager');
        $templateManager = $this->get('phlexible_media_template.template_manager');
        $mediaTypeManager = $this->get('phlexible_media_type.media_type_manager');
        $delegateService = $this->get('phlexible_media_cache.image_delegate.service');
        $volumeManager = $this->get('phlexible_media_manager.volume_manager');

        try {
            $cacheItem = $cacheManager->findByTemplateAndFile($templateKey, $fileId, $fileVersion);
        } catch (\Exception $e) {
            $cacheItem = null;
        }

        $template = $templateManager->find($templateKey);

        if ($cacheItem) {
            if ($cacheItem->getCacheStatus() === CacheItem::STATUS_WAITING) {
                $cacheItem = $this->doCache($fileId, $fileVersion, $template, $cacheItem);
            } elseif ($cacheItem->getCacheStatus() === CacheItem::STATUS_MISSING) {
                $cacheItem = $this->doCache($fileId, $fileVersion, $template, $cacheItem);
            }

            if ($cacheItem && $cacheItem->getCacheStatus() === CacheItem::STATUS_OK) {
                $storageKey = $template->getStorage();
                $storage = $storageManager->get($storageKey);
                $filePath = $storage->getLocalPath($cacheItem);

                if (!file_exists($filePath)) {
                    $filePath = null;
                    $cacheItem = $this->doCache($fileId, $fileVersion, $template, $cacheItem);

                    if ($cacheItem && $cacheItem->getCacheStatus() === CacheItem::STATUS_OK) {
                        $storageKey = $template->getStorage();
                        $storage = $storageManager->get($storageKey);
                        $filePath = $storage->getLocalPath($cacheItem);
                    }
                }
            }

            if ($cacheItem) {
                $mimeType = $cacheItem->getMimeType();
            }
        } else {
            $cacheItem = $this->doCache($fileId, $fileVersion, $template);

            if ($cacheItem) {
                if ($cacheItem->getCacheStatus() === CacheItem::STATUS_OK) {
                    $storageKey = $template->getStorage();
                    $storage = $storageManager->get($storageKey);
                    $filePath = $storage->getLocalPath($cacheItem);
                }
                $mimeType = $cacheItem->getMimeType();
            }
        }

        if (empty($filePath)) {
            if (!$template instanceof ImageTemplate) {
                return new Response('Not found', 404);
            }

            $file = $volumeManager->getByFileId($fileId)->findFile($fileId);
            $mediaType = $mediaTypeManager->find(strtolower($file->getMediaType()));
            $filePath = $delegateService->getClean($template, $mediaType, true);
            $mimeType = 'image/gif';
        }

        $response = new BinaryFileResponse($filePath, 200, array('Content-Type' => $mimeType));

        return $response;
    }
195091
public function uploadImageAction(Request $request): Response
    {
        if ($this->isValidCsrfToken($request)) {
            $data = new ImageAssetUploadData(
                $request->files->get(self::FILE_KEY),
                $request->request->get(self::LANGUAGE_CODE_KEY)
            );

            $errors = $this->validator->validate($data);
            if ($errors->count() === 0) {
                try {
                    $file = $data->getFile();

                    $content = $this->imageAssetMapper->createAsset(
                        $file->getClientOriginalName(),
                        new ImageValue([
                            'path' => $file->getRealPath(),
                            'fileSize' => $file->getSize(),
                            'fileName' => $file->getClientOriginalName(),
                            'alternativeText' => null,
                        ]),
                        $data->getLanguageCode()
                    );

                    return new JsonResponse([
                        'destinationContent' => [
                            'id' => $content->contentInfo->id,
                            'name' => $content->getName(),
                            'locationId' => $content->contentInfo->mainLocationId,
                        ],
                        'value' => $this->imageAssetMapper->getAssetValue($content),
                    ]);
                } catch (Exception $e) {
                    return $this->createGenericErrorResponse($e->getMessage());
                }
            } else {
                return $this->createInvalidInputResponse($errors);
            }
        }

        return $this->createInvalidCsrfResponse();
    }
543289
public function upload(Request $request)
    {
        $validation = $this->validation->check([
            'location' => [],
        ]);

        if (!$validation['errors']) {
            $file = $request->file('location');
            $fileSaved = $this->fileService->saveFile($file, 'files/');
            $fileSaved['name'] = CryptoService::encrypt($fileSaved['name']);
            $fileSaved['mime'] = $file->getClientMimeType();
            $fileSaved['size'] = $file->getClientSize();
            $response = $this->responseService->apiResponse('success', $fileSaved);
        } else {
            $response = $this->responseService->apiErrorResponse($validation['errors'], $validation['inputs']);
        }

        return $response;
    }
439467
public function store(UploadImageRequest $request)
    {
        $upload = $this->uploader->upload($request->file('image'), storage_path('app/laramanager/images'));

        return $this->imageRepository->create($upload->toArray());
    }
648555
public function uploadAction(Request $request)
    {
        $files = $this->uploadFiles($request);
        $data = [];

        foreach ($files as $file) {
            $data[] = $this->serializer->serialize($file);
        }

        return new JsonResponse($data, 200);
    }
721604
public function saveAction(Request $request)
    {
        $all = $request->get('all');
        $action = $request->get('action');
        $tempId = $request->get('temp_id');

        $metaData = $request->get('meta', null);
        if ($metaData) {
            $metaData = json_decode($metaData, true);
        }

        $tempHandler = $this->get('phlexible_media_manager.upload.temp_handler');

        if ($all) {
            $tempHandler->handleAll($action);
        } else {
            $file = $tempHandler->handle($action, $tempId);

            if ($file && $metaData) {
                $this->saveMeta($file, $metaData);
            }
        }

        return new ResultResponse(true, ($all ? 'All' : 'File').' saved with action '.$action);
    }
1207962
private function getUploadedFileFromRequest(Request $request)
    {
        $file = false;

        if ($request->files instanceof FileBag && $request->files->count() > 0) {
            if ($request->files->count() > 1) {
                throw new InvalidArgumentException('Only 1 file upload per requests allowed.');
            }
            $files = $request->files->all();
            $file = reset($files);
            if ($this->allowedMimeTypes && !in_array($file->getMimeType(), $this->allowedMimeTypes)) {
                throw new InvalidArgumentException('File mime type: '.$file->getMimeType().' is not allowed.');
            }
        }

        return $file;
    }
562855
public function searchMedia(Request $request)
    {
        return Search::media($request->term, $request->from, $request->to, $request->type, "created_at", "DESC", $request->page);
    }
30501
public function imageUploadAction(Request $request)
    {
        $image = new ImageField();
        /* @var $form Form */
        $form = $this->createForm(new UploadImage(), $image);
        $form->handleRequest($request);

        if (!$form->isValid()) {
            $errors = $form->getErrors();

            return new JsonResponse(['error' => $this->get('translator')->trans($errors[0]->getMessage())], 404);
        }

        // try upload file
        try {
            $this->get('anime_db.downloader')->imageField($image);

            return new JsonResponse([
                'path' => $image->getFilename(),
                'image' => $image->getWebPath(),
            ]);
        } catch (\InvalidArgumentException $e) {
            return new JsonResponse(['error' => $this->get('translator')->trans($e->getMessage())], 404);
        }
    }