Determine the list of files to upload.

@param Request $request
@param string  $namespace
@param string  $files

@return array
487062
private function getFilesToProcess(Request $request, $namespace, $files = null)
    {
        $this->app['upload.namespace'] = $namespace;

        if ($files === null) {
            $files = $request->files->get($namespace);
        }

        if (!$files) {
            return [];
        }
        $filesToProcess = [];
        foreach ($files as $file) {
            if ($file instanceof UploadedFile) {
                $filesToProcess[] = [
                    'name'     => $file->getClientOriginalName(),
                    'tmp_name' => $file->getPathname(),
                ];
            } else {
                $filesToProcess[] = $file;
            }
        }

        return $filesToProcess;
    }
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;
    }
999076
public function settingsAction(Request $request, $namespace = null)
    {
        $admin = $this->getAdmin();

        $admin->checkAccess('settings');

        if (null === $namespace) {
            $namespace = $admin->getSettingsNamespace();
        }

        $manager = $this->getSettingsManager();
        $settings = $manager->load($namespace);

        $form = $this
            ->getSettingsFormFactory()
            ->create($namespace);

        $form->setData($settings);

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);

            if ($form->isValid()) {
                $manager->save($form->getData());

                $message = $this->getTranslator()->trans('settings.updated_successful');
                $this->get('session')->getFlashBag()->add('sonata_flash_success', $message);

                return $this->redirect($request->headers->get('referer'));
            }
        }

        $admin_pool = $this->get('sonata.admin.pool');

        return $this->renderWithExtraParams(
            'CompoCoreBundle:Admin:settings.html.twig',
            [
                'action' => 'settings',
                'breadcrumbs_builder' => $this->get('sonata.admin.breadcrumbs_builder'),
                'admin' => $admin,
                'base_template' => 'CompoSonataAdminBundle::standard_layout_compo.html.twig',

                'settings' => $settings,
                'form' => $form->createView(),
                'admin_pool' => $admin_pool,
                'translation_domain' => $admin->getTranslationDomain(),
            ]
        );
    }
634535
public function deleteFile(Request $request)
    {
        $namespace = $request->request->get('namespace');
        $filename = $request->request->get('filename');

        try {
            $this->filesystem()->delete("$namespace://$filename");

            return $this->json($filename, Response::HTTP_OK);
        } catch (ExceptionInterface $e) {
            $msg = Trans::__('Unable to delete file: %FILE%', ['%FILE%' => $filename]);
            $this->logException($msg, $e);

            return $this->json(
                $msg,
                $e instanceof FileNotFoundException ? Response::HTTP_NOT_FOUND : Response::HTTP_INTERNAL_SERVER_ERROR
            );
        }
    }
1233379
private function parseUploadedFiles(Request $request)
    {
        $bodyParams = $request->all();
        if (!isset($bodyParams['map'])) {
            throw new RequestError('The request must define a `map`');
        }

        $map = json_decode($bodyParams['map'], true);
        $result = json_decode($bodyParams['operations'], true);
        if (isset($result['operationName'])) {
            $result['operation'] = $result['operationName'];
            unset($result['operationName']);
        }

        foreach ($map as $fileKey => $locations) {
            foreach ($locations as $location) {
                $items = &$result;
                foreach (explode('.', $location) as $key) {
                    if (!isset($items[$key]) || !is_array($items[$key])) {
                        $items[$key] = [];
                    }
                    $items = &$items[$key];
                }

                $items = $request->allFiles()[$fileKey];
            }
        }

        $request->replace($result);

        return $request;
    }
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;
    }
907640
public function upload(ThumbnailRequest $request)
    {
        $crudeName = $request->input('crudeName');
        $crude = CrudeInstance::get($crudeName);
        $column = $request->input('columnName');
        $file = $request->file()['file'];

        $id = $request->input('modelId');
        $model = $crude->uploadThumbnailByIdAndColumn($id, $column, $file);

        return ['success' => true, 'model' => $model];
    }
827324
public function listAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            throw new NotFoundHttpException();
        }

        $root = $this->getFolderRepository()->findRoot();
        if (null !== $id = $request->query->get('folderId')) {
            if (!$this->activateFolderById($id, $root)) {
                $root->setActive(true);
            }
        } else {
            $root->setActive(true);
        }

        $folders = $this->get('jms_serializer')->serialize(
            array($root),
            'json',
            SerializationContext::create()->setGroups(array('Manager'))
        );

        $response = new Response($folders);
        $response->headers->add(array('Content-Type' => 'application/json'));

        return $response;
    }
891633
public function get_file(Request $request)
    {
        $filepath = $request->input('filepath');
        $data = file_get_contents(base_path($filepath));
        echo $data;
    }
949704
public function renameFile(Request $request)
    {
        $namespace = $request->request->get('namespace');
        $parent = $request->request->get('parent');
        $oldName = $request->request->get('oldname');
        $newName = $request->request->get('newname');

        if (!$this->isExtensionChangedAndIsChangeAllowed($oldName, $newName)) {
            return $this->json(Trans::__('general.phrase.only-root-change-file-extensions'), Response::HTTP_FORBIDDEN);
        }

        if ($this->validateFileExtension($newName) === false) {
            return $this->json(
                sprintf("File extension not allowed: %s", $newName),
                Response::HTTP_BAD_REQUEST
            );
        }

        try {
            $this->filesystem()->rename("$namespace://$parent/$oldName", "$parent/$newName");

            return $this->json($newName, Response::HTTP_OK);
        } catch (ExceptionInterface $e) {
            $msg = Trans::__('Unable to rename file: %FILE%', ['%FILE%' => $oldName]);
            $this->logException($msg, $e);

            if ($e instanceof FileExistsException) {
                $status = Response::HTTP_CONFLICT;
            } elseif ($e instanceof FileNotFoundException) {
                $status = Response::HTTP_NOT_FOUND;
            } else {
                $status = Response::HTTP_INTERNAL_SERVER_ERROR;
            }

            return $this->json($msg, $status);
        }
    }
765451
public function loadAction(Request $request)
    {
        $repo = $this->getDoctrine()->getRepository('LibrinfoMediaBundle:File');
        $files = [];

        foreach ($request->get('load_files') as $key => $id) {
            $file = null;

            $dispatcher = $this->get('event_dispatcher');

            $event = new GenericEvent(
                [
                    'request' => $request,
                    'context' => [
                        'key'  => $key,
                        'id'   => $id,
                        'file' => $file,
                    ],
                ], [
                    'file'  => null,
                    'files' => $files,
                ]
            );
            $dispatcher->dispatch(UploadControllerEventListener::PRE_GET_ENTITY, $event);

            $file = $event->getArgument('file');

            if ($file) {
                $file->setFile($file->getBase64File());
            }

            $event = new GenericEvent(
                [
                    'request' => $request,
                    'context' => [
                        'key'  => $key,
                        'id'   => $id,
                        'file' => $file,
                    ],
                ], [
                    'file'  => $file,
                    'files' => $files,
                ]
            );
            $dispatcher->dispatch(UploadControllerEventListener::POST_GET_ENTITY, $event);

            $file = $event->getArgument('file');

            if ($file) {
                $files[] = $file;
            }
        }

        return new JsonResponse($files, 200);
    }
156196
protected function upload_from_file( $files, $headers ) {
		if ( empty( $files ) ) {
			return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
		}

		// Verify hash, if given.
		if ( ! empty( $headers['content_md5'] ) ) {
			$content_md5 = array_shift( $headers['content_md5'] );
			$expected = trim( $content_md5 );
			$actual = md5_file( $files['file']['tmp_name'] );
			if ( $expected !== $actual ) {
				return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
			}
		}

		// Pass off to WP to handle the actual upload.
		$overrides = array(
			'test_form'   => false,
		);
		// Bypasses is_uploaded_file() when running unit tests.
		if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
			$overrides['action'] = 'wp_handle_mock_upload';
		}

		// Include admin functions to get access to wp_handle_upload().
		require_once ABSPATH . 'wp-admin/includes/admin.php';
		$file = wp_handle_upload( $files['file'], $overrides );

		if ( isset( $file['error'] ) ) {
			return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
		}

		return $file;
	}
634783
final public function prepareMultipartRequestPayloads(array $headers = [], array $body = [], array $files = []): array
    {
        $multipart = (($headers['Content-Type'] ?? null) == 'multipart/form-data');

        if (empty($files) && ! $multipart) {
            return [$headers, $body];
        }

        $builder = new Builder(StreamFactoryDiscovery::find());

        $this->addFilesToMultipartBuilder($builder, $files);
        $this->addBodyToMultipartBuilder(
            $builder, $this instanceof Filterable ? $this->filterRequest($body) : $body
        );

        $headers['Content-Type'] = 'multipart/form-data; boundary='.$builder->getBoundary();

        return [$headers, $builder->build()];
    }
347356
public function getRequiredFiles($namespace)
    {
        $files = [];

        // First loop is finding 'production' config for each basepath:
        foreach ($this->configPaths as $basePath) {
            $configFileCandidate = $basePath.'/'.$namespace.'.php';
            if (file_exists($configFileCandidate)) {
                $files[] = [
                    'path' => realpath($configFileCandidate),
                    'environment' => null
                ];
            }
        }

        // Second loop is finding 'environment level' config for each basepath:
        if ($this->config->getEnvironment() !== null) {
            foreach ($this->configPaths as $basePath) {
                $envConfigFileCandidate = $basePath.'/'.$this->config->getEnvironment().'/'.$namespace.'.php';
                if (file_exists($envConfigFileCandidate)) {
                    $files[] = [
                        'path' => realpath($envConfigFileCandidate),
                        'environment' => $this->config->getEnvironment()
                    ];
                }
            }
        }
        return $files;
    }
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);
    }
630836
public function folder(Request $request)
    {
        $json = [];

        $validator = $this->validatorFolder($request->all())->fails();

        if ($validator) {
            $json['error'] = trans('admin::image.error.folder_alpha_num');
        }

        if (!$json) {
            $dir = '';
            if ($request->get('directory')) {
                $dir = $request->get('directory') . '/';
            }
            $dir .= $request->get('folder');
            $result = $this->storage->makeDirectory($dir);

            if ($result) {
                $json['success'] = trans('admin::image.success.folder');
            } else {
                $json['error'] = trans('admin::image.error.folder');
            }
        }

        return response()
            ->json($json);
    }
1047349
public function upload(Request $request)
    {
        $json = [];
        foreach ($request->file('file') as $file) {
            $this->storage->putFile($request->get('directory'), $file);
        }

        $json['success'] = trans('admin::image.success.upload');

        return response()
            ->json($json);
    }