Route to handle file uploads.

@param Request $request
@param string  $namespace

@return \Symfony\Component\HttpFoundation\JsonResponse
194330
public function uploadNamespace(Request $request, $namespace)
    {
        if ($handler = $request->get('handler')) {
            // Use custom handlers
            if (is_array($handler)) {
                return $this->processCustomUploadHandler($request, $handler);
            }
            list($namespace, $prefix) = $this->parser($handler);
            $this->app['upload.namespace'] = $namespace;
            $this->app['upload.prefix'] = $prefix;
        } else {
            $namespace = $this->app['upload.namespace'];
        }

        // Perform the file upload actions and collect the results
        $fileUpload = $this->handleUploadFiles($request, $namespace);

        return $this->json($fileUpload, Response::HTTP_OK, ['Content-Type' => 'text/plain']);
    }
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')
        ]);
    }
270956
public function handleUpload(SS_HTTPRequest $request)
    {
        $request->setUrl('upload');

        /** @var Folder $folder */
        $folder = Folder::get()->byID($request->param('FolderID'));

        /** @var FileAttachmentField $uploader */
        $uploader = FileAttachmentField::create('dummy');

        if ($folder) {
            $uploader->setFolderName(self::remove_assets_dir($folder->Filename));
        } else {
            $uploader->setFolderName('/');
        }

        /** @var SS_HTTPResponse $httpResponse */
        $httpResponse = $uploader->handleRequest($request, DataModel::inst());

        if ($httpResponse->getStatusCode() !== 200) {
            return $httpResponse;
        }

        $ids = $httpResponse->getBody();
        $files = File::get()->byIDs(explode(',', $ids));
        $result = array();

        foreach ($files as $f) {
            $result[] = $this->createFileJson($f, $folder);
        }

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
959717
public function uploadAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $uploadFile = $em->getRepository('CompoImportBundle:UploadFile')->find($request->get('import_id'));

        $countImport = $em->getRepository('CompoImportBundle:ImportLog')->count([
            'uploadFile' => $uploadFile->getId(),
        ]);

        $data = $em->getRepository('CompoImportBundle:ImportLog')->pagerfanta($request);

        $paginator = $this->get('knp_paginator');

        /** @var SlidingPagination $pagination */
        $pagination = $paginator->paginate(
            $data,
            $request->query->getInt('page', 1),
            100
        );

        $pagination->setCustomParameters(['type' => $request->get('type', 'all')]);

        $pagination->setParam('type', $request->get('type', 'all'));

        $stats = [
            0 => [
                'status' => 0,
                'count' => 0,
            ],
            1 => [
                'status' => 1,
                'count' => 0,
            ],
            2 => [
                'status' => 2,
                'count' => 0,
            ],
            3 => [
                'status' => 3,
                'count' => 0,
            ],
        ];

        foreach ($stats as $statKey => $stat) {
            $stats[$statKey]['count'] = $em->getRepository('CompoImportBundle:ImportLog')->count([
                'uploadFile' => $uploadFile->getId(),
                'status' => $stat['status'],
            ]);
        }

        return $this->renderWithExtraParams('@CompoImport/Default/upload.html.twig', [
            'uploadFile' => $uploadFile,
            'paginator' => $pagination,
            'action' => 'upload',
            'admin' => $this->admin,
            'stats' => $stats,

            'countImport' => $countImport,
            'base_template' => $this->getBaseTemplate(),
        ]);
    }
581484
public function uploadAction(Request $request)
    {
        $this->checkToolAccess();

        $files = $request->files->all();
        $data = null;

        if (1 === count($files)) {
            foreach ($files as $file) {
                $data = file_get_contents($file);
            }
        } else {
            return new JsonResponse('No uploaded file', 500);
        }

        return new JsonResponse($data, 200);
    }
1119097
public function apiCreateFile(HTTPRequest $request)
    {
        $data = $request->postVars();

        // When creating new files, rename on conflict
        $upload = $this->getUpload();
        $upload->setReplaceFile(false);

        // CSRF check
        $token = SecurityToken::inst();
        if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
            $this->jsonError(400);
            return null;
        }

        // Check parent record
        /** @var Folder $parentRecord */
        $parentRecord = null;
        if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) {
            $parentRecord = Folder::get()->byID($data['ParentID']);
        }
        $data['Parent'] = $parentRecord;

        $tmpFile = $request->postVar('Upload');
        if (!$upload->validate($tmpFile)) {
            $errors = $upload->getErrors();
            $message = array_shift($errors);
            $this->jsonError(400, $message);
            return null;
        }

        // TODO Allow batch uploads
        $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name']));
        /** @var File $file */
        $file = Injector::inst()->create($fileClass);

        // check canCreate permissions
        if (!$file->canCreate(null, $data)) {
            $this->jsonError(
                403,
                _t(__CLASS__.'.CreatePermissionDenied', 'You do not have permission to add files')
            );
            return null;
        }

        $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/');
        if (!$uploadResult) {
            $this->jsonError(
                400,
                _t(__CLASS__.'.LoadIntoFileFailed', 'Failed to load file')
            );
            return null;
        }

        $file->ParentID = $parentRecord ? $parentRecord->ID : 0;
        $file->write();

        $result = [
            $this->getObjectFromData($file, false)
        ];

        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
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]);
    }
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);
    }
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;
    }
758319
public function load($environment, $namespace)
    {

        //evironments = /config/<environment>/namespace.ini[section].key
        $file = $this->directory;
        $file .= !empty($environment) ? $environment . DS : DS;
        $file .= $namespace;
        $file .= $this->extension;


        //Check that we have a file named namespace
        if (!array_key_exists($this->extension, $this->handlers)) {
            throw new \Exception("config file handler for {$this->extension} does not exists");
        }


        $handler = $this->handlers[$this->extension];
        $params = $handler->readParams($file);


        return $params;
    }
193950
protected function routesRegister(string $file, string $namespace)
    {
        $this->app->router->group([
            'namespace' => $namespace,
        ], function ($router) use ($file) {
            require $file;
        });
    }
238224
private function pushRequestsInDefinition($alias_namespace, $requests_directory, &$default_definitions)
    {
        $request_files = get_files($requests_directory);
        if (!empty($request_files))
        {
            $requests = array_map(function($request) use($requests_directory) {
                $new_request = str_replace("{$requests_directory}/", "", $request);
                return basename(str_replace("/", "\\", $new_request), ".php");
            }, $request_files);

            $errors = [];

            foreach ($requests as $request) {
                if ($alias_namespace === "\\")
                {
                    $request_definition = get_app_namespace() . "Requests\\{$request}";
                }
                else
                {
                    $module_name = str_replace("App\\", "", $alias_namespace);

                    $request_sub_namespace = str_replace(app_path() . "/{$module_name}/Requests", "", $requests_directory);
                    $request_sub_namespace = str_replace("/", "\\", $request_sub_namespace);

                    $request_definition = "{$alias_namespace}Requests\\{$request}";
                }

                if (!array_key_exists("{$request_definition}", $default_definitions))
                {
                    $default_definitions["{$request_definition}"] = function(ContainerInterface $c) use ($request_definition)
                    {
                        return new $request_definition($c->get('request'));
                    };
                }
                else
                {
                    $errors[] = "{$request} is already exist inside of definitions.";
                }
            }

            if (!empty($errors))
            {
                exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
            }
        }
        else
        {
            exit("Error: No request found in {$requests_directory} path.");
        }
    }
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;
    }
804526
static function load($namespace,$folder = ''){
	
		if(!isset(self::$files[$namespace])){
			$ns = self::getName($namespace,$folder);
			
			if(!file_exists($ns->path)){
				Exceptions::showError('Server Error','Missing File '.$ns->path.' Not Found');
				exit;
			}
			
			require_once $ns->path;
			self::$files[$namespace] = $ns;
		}
	}
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
            );
        }
    }
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();
    }
570409
public function jsonSaveAction(Request $request)
    {
        //@FIXME: This code need to be moved to ContentController somehow.
        $this->save($request);

        $response = new Response(json_encode(['status' => 'ok']));
        $response->headers->set("Content-Type", 'application/json');

        return $response;
    }