Upload a media file.

@param  \Illuminate\Http\Request  $request

@return \Illuminate\Http\JsonResponse
433311
public function uploadMedia(Request $request)
    {
        $this->authorize(MediasPolicy::PERMISSION_CREATE);

        // TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
        $validator = validator($request->all(), [
            'location' => ['required', 'string'],
            'medias'   => ['required', 'array'],
            'medias.*' => ['required', 'file']
        ]);

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

        $uploaded = $this->media->storeMany(
            $request->get('location'), $request->file('medias')
        );

        return $this->jsonResponseSuccess([
            'data' => compact('uploaded')
        ]);
    }
1029653
public function medialinkAction(Request $request)
    {
        $fileId = $request->get('file_id');
        $router = $this->get('router');

        $urls = [
            'download' => $router->generate('frontendmedia_download', ['fileId' => $fileId], UrlGeneratorInterface::ABSOLUTE_URL),
            'inline' => $router->generate('frontendmedia_inline', ['fileId' => $fileId], UrlGeneratorInterface::ABSOLUTE_URL),
            'icon' => $router->generate('frontendmedia_icon', ['fileId' => $fileId, 'size' => 16], UrlGeneratorInterface::ABSOLUTE_URL),
        ];

        return new JsonResponse($urls);
    }
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]);
    }
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]);
    }
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;
    }
968561
public function addAction(Request $request): Response
    {
        $form = $this->formFactory->addTranslation();
        $form->handleRequest($request);

        /** @var TranslationAddData $data */
        $data = $form->getData();
        $location = $data->getLocation();

        if ($form->isSubmitted()) {
            $result = $this->submitHandler->handle($form, function (TranslationAddData $data) {
                $location = $data->getLocation();
                $contentInfo = $location->getContentInfo();
                $language = $data->getLanguage();
                $baseLanguage = $data->getBaseLanguage();

                return new RedirectResponse($this->generateUrl('ezplatform.content.translate', [
                    'contentId' => $contentInfo->id,
                    'fromLanguageCode' => null !== $baseLanguage ? $baseLanguage->languageCode : null,
                    'toLanguageCode' => $language->languageCode,
                ]));
            });

            if ($result instanceof Response) {
                return $result;
            }
        }

        $redirectionUrl = null !== $location
            ? $this->generateUrl('_ezpublishLocation', ['locationId' => $location->id])
            : $this->generateUrl('ezplatform.dashboard');

        return $this->redirect($redirectionUrl);
    }
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;
    }
292920
public function store(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $this->manager->resetPath($request->path);

            if (!$this->manager->isSafe($file->getClientOriginalExtension(), $file->getMimeType())) {
                return $this->json(['Uploading file is not safe and could not be uploaded.'], 422);
            }

            $blob = $this->manager->upload($file);

            return $this->json($blob);
        }

        return $this->json(['File not presented for upload.'], 422);
    }
116041
public function upload(HTTPRequest $request)
    {
        if ($this->isDisabled() || $this->isReadonly()) {
            return $this->httpError(403);
        }

        // CSRF check
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        $tmpFile = $request->postVar('Upload');
        /** @var File $file */
        $file = $this->saveTemporaryFile($tmpFile, $error);

        // Prepare result
        if ($error) {
            $result = [
                'message' => [
                    'type' => 'error',
                    'value' => $error,
                ]
            ];
            $this->getUpload()->clearErrors();
            return (new HTTPResponse(json_encode($result), 400))
                ->addHeader('Content-Type', 'application/json');
        }

        // We need an ID for getObjectFromData
        if (!$file->isInDB()) {
            $file->write();
        }

        // Return success response
        $result = [
            AssetAdmin::singleton()->getObjectFromData($file)
        ];

        // Don't discard pre-generated client side canvas thumbnail
        if ($result[0]['category'] === 'image') {
            unset($result[0]['thumbnail']);
        }
        $this->getUpload()->clearErrors();
        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
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),
        ]);
    }
155948
public function bulkMoveAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $mediaRepo = $em->getRepository('KunstmaanMediaBundle:Media');
        $form = $this->createForm(BulkMoveMediaType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Folder $folder */
            $folder = $form->getData()['folder'];
            $mediaIds = explode(',', $form->getData()['media']);

            $mediaRepo->createQueryBuilder('m')
                ->update()
                ->set('m.folder', $folder->getId())
                ->where('m.id in (:mediaIds)')
                ->setParameter('mediaIds', $mediaIds)
                ->getQuery()
                ->execute();

            $this->addFlash(FlashTypes::SUCCESS, $this->get('translator')->trans('media.folder.bulk_move.success.text'));

            return new JsonResponse(
                [
                    'Success' => 'The media is moved',
                ]
            );
        }

        return $this->render(
            '@KunstmaanMedia/Folder/bulk-move-modal_form.html.twig',
            [
                'form' => $form->createView(),
            ]
        );
    }
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);
    }
562728
def media_upload(self, filename, *args, **kwargs):
        
        f = kwargs.pop('file', None)
        headers, post_data = API._pack_image(filename, 4883, form_field='media', f=f)
        kwargs.update({'headers': headers, 'post_data': post_data})

        return bind_api(
            api=self,
            path='/media/upload.json',
            method='POST',
            payload_type='media',
            allowed_param=[],
            require_auth=True,
            upload_api=True
        )(*args, **kwargs)
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);
    }
995258
public function saveAction(Request $request)
    {
        $repository = $this->get('phlexible_media_template.template_manager');

        $templateKey = $request->get('template_key');
        $params = $request->request->all();

        unset($params['template_key'],
        $params['module'],
        $params['controller'],
        $params['action']);

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

        $params = $this->fixParams($params);

        foreach ($params as $key => $value) {
            $template->setParameter($key, $value);
        }

        $repository->updateTemplate($template);

        return new ResultResponse(true, 'Media template "'.$template->getKey().'" saved.');
    }
600962
public function getMediasAction(Request $request)
    {
        if (!$request->query->has('filters')) {
            return $this->createResponse(array());
        }

        $mediaManager = $this->getMediaManager();

        $filtersKeys = explode(',', $request->query->get('filters'));
        $medias = $mediaManager->findAllByFiltersKeys($filtersKeys);

        return $this->createResponse($medias);
    }
1068499
public function createAction(Request $request)
    {
        $parentId = $request->get('parent_id');
        $name = $request->get('folder_name');

        $volume = $this->get('phlexible_media_manager.volume_manager')->getByFolderId($parentId);
        $parentFolder = $volume->findFolder($parentId);

        try {
            $folder = $volume->createFolder($parentFolder, $name, array(), $this->getUser()->getId());

            return new ResultResponse(true, 'Folder created.', [
                'folder_id' => $folder->getId(),
                'folder_name' => $folder->getName(),
            ]);
        } catch (AlreadyExistsException $e) {
            return new ResultResponse(false, $e->getMessage(), [
                'folder_name' => 'Folder already exists.',
            ]);
        } catch (\Exception $e) {
            return new ResultResponse(false, $e->getMessage());
        }
    }