Return File in passed request if ok, otherwise return null
@param string $uploadField
@param Request $request
@return null|UploadedFile
429450
public static function getFileSafe(
        string $uploadField,
        Request $request
    ) {
        if (!$request) {
            return null;
        }

        $uploadedFile = $request->file($uploadField);

        //check type because request file method, may returns UploadedFile, array or null
        if (!is_a($uploadedFile, UploadedFile::class)) {
            return null;
        }

        return $uploadedFile;
    }
647764
public function addUploadedFile(UploadedFileInterface $upload, string $field = null, array $crop = null): string
    {
        $tmp_dir = $this->getTmpDir();
        $tmp_name = Utils::generateRandomString(12);
        $name = $upload->getClientFilename();

        // Prepare upload data for later save
        $data = [
            'name' => $name,
            'type' => $upload->getClientMediaType(),
            'size' => $upload->getSize(),
            'tmp_name' => $tmp_name
        ];

        Folder::create($tmp_dir);
        $upload->moveTo("{$tmp_dir}/{$tmp_name}");

        $this->addFileInternal($field, $name, $data, $crop);

        return $name;
    }
1171496
protected function getUploadFileMethod(array $fields, $withFormRequest = false)
    {
        if (!$withFormRequest && Config::createMoveFileMethod() && $this->containsfile($fields)) {
            $stubName = 'controller-upload-method';
            if (Helpers::isNewerThanOrEqualTo()) {
                $stubName .= '-5.3';
            }

            return $this->getStubContent($stubName, $this->getTemplateName());
        }

        return '';
    }
1029309
public function ckeditorAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $funcNumber = $request->get('CKEditorFuncNum');

        if ($file = $request->files->get('upload')) {
            $supportedTypes = array(
                'image/jpeg',
                'image/png'
            );

            if ($file->getSize() > static::FILE_SIZE_MAX) {
                return $this->getCkeditorResponse(
                    'The uploaded file is too large. Please limit the file to under ' . (self::FILE_SIZE_MAX / 1024) . 'KiB',
                    '',
                    $funcNumber
                );
            }

            try {
                $uploadDir = $this->get('kernel')->getRootDir() . static::CKEDITOR_UPLOAD_DIR;
                $file      = File::createFromUploadedFile($file, $uploadDir);
                $file->moveUploadedFile();

                $em->persist($file);
                $em->flush();
            } catch (\Exception $e) {
                return $this->getCkeditorResponse($e->getMessage(), '', $funcNumber);
            }
        }

        if (!($file && file_exists($file->getPath()))) {
            return $this->getCkeditorResponse('There was an error while uploading the file. The file was not copied to the upload directory', '', $funcNumber);
        }

        $src = $this->generateUrl('file_view', array('id' => $file->getId()), true);

        return $this->getCkeditorResponse('Upload Successful', $src, $funcNumber);
    }
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(),
        ]);
    }
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;
    }
1319806
@Route(method = HttpMethod.POST, uri = "/")
    public Result upload(@FormParameter("upload") FileItem uploaded) {
        return ok("File " + uploaded.name() + " of type " + uploaded.mimetype() +
                " uploaded (" + uploaded.size() + " bytes)");
    }
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,
        ]);
    }
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);
    }
464438
private UploadFile getUploadFileFromSession(HttpServletRequest request,
                                              String id) {
    UploadFile uploadFile = null;
    boolean found = false;
    try {
      HttpSession session = request.getSession(true);
      Collection uploadList = (Collection) session.getAttribute(PIC_NAME_PACKAGE);
      if (uploadList == null)
        return null;
      Iterator iter = uploadList.iterator();
      while (iter.hasNext()) {
        uploadFile = (UploadFile) iter.next();
        if (uploadFile.getId().equals(id)){
          found = true;
          break;
        }else if (uploadFile.getTempId().equals(id)){
          found = true;
          break;
        }
      }
      if (!found )  uploadFile = null;
    } catch (Exception ex) {
      Debug.logError("[JdonFramework] getUploadFileSession error" + ex, module);

    }
    return uploadFile;

  }
1304508
public function uploadImage($imageFile, $field = null)
    {
        $this->uploadFieldName = $this->getUploadFieldName($field);
        $this->uploadFieldOptions = $this->getUploadFieldOptions($this->uploadFieldName);

        // validate it
        $this->validateImage($imageFile, $this->uploadFieldName, $this->uploadFieldOptions);

        // handle upload
        $filePath = $this->hasFileField($this->uploadFieldName)
            ? $this->handleFileUpload($imageFile)
            : $this->handleImageUpload($imageFile);

        // hold old file
        $currentFile = $this->getOriginal($this->uploadFieldName);

        // update the model with field name
        $this->updateModel($filePath, $this->uploadFieldName);

        // delete old file
        if ($currentFile != $filePath) {
            $this->deleteImage($currentFile);
        }
    }
415956
private function handleUploadFiles(Request $request, $namespace, $files = null)
    {
        $filesToProcess = $this->getFilesToProcess($request, $namespace, $files);

        /** @var \Sirius\Upload\Result\Collection $result */
        $result = $this->app['upload']->process($filesToProcess);

        if ($result->isValid()) {
            if (!$this->app['config']->get('general/upload/autoconfirm')) {
                // Remove the .lock file attached to the file
                $result->confirm();
            }

            $successfulFiles = [];
            foreach ($result as $resultFile) {
                $successfulFiles[] = $this->filesystem()->toJs($namespace . '://' . $resultFile->name);
            }

            return $successfulFiles;
        }

        // The file that was saved during process() has a .lock file attached
        // and can now be cleared, in the case where form processing fails
        try {
            $result->clear();
        } catch (\Exception $e) {
            // It's an error state anyway
        }

        $errorFiles = [];
        foreach ($result as $resultFile) {
            $errors = $resultFile->getMessages();
            $errorFiles[] = [
                    'name'  => $resultFile->original_name,
                    'error' => (string) $errors[0],
                ];
        }

        return $errorFiles;
    }
1274350
public function fancyUpload(Request $request, $transformConfig = [], $appendedPath = null)
    {
        if ($request->hasFile('file')) {
            foreach ($request->file('file') as $file) {
                if ($file->isValid()) {
                    $uploadedFile = $this->uploadFile($file, $transformConfig, $appendedPath);

                    // Generate return information
                    if ($uploadedFile) {
                        return $this->generateFancyUploadResponse($request, $uploadedFile);
                    }
                } else {
                    throw new UploadException('File not valid.');
                }
            }
        }

        throw new UploadException('No valid files to upload');
    }
56582
public function upload(Request $request)
    {
        try {
            $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix();

            $allowedImageMimeTypes = [
                'image/jpeg',
                'image/png',
                'image/gif',
                'image/bmp',
                'image/svg+xml',
            ];

            if (in_array($request->file->getMimeType(), $allowedImageMimeTypes)) {
                $file = $request->file->store($request->upload_path, $this->filesystem);

                $image = Image::make($realPath.$file);

                if ($request->file->getClientOriginalExtension() == 'gif') {
                    copy($request->file->getRealPath(), $realPath.$file);
                } else {
                    $image->orientate()->save($realPath.$file);
                }
            } else {
                $file = $request->file->move($realPath, $request->file->getClientOriginalName());
            }

            $success = true;
            $message = __('admin.media.success_uploaded_file');
            $path = preg_replace('/^public\//', '', $file);
        } catch (Exception $e) {
            $success = false;
            $message = $e->getMessage();
            $path = '';
        }

        return response()->json(compact('success', 'message', 'path'));
    }
23691
public UploadFile getUploadFile(HttpServletRequest request, String id) {
    UploadFile uploadFile = null;
    Debug.logVerbose("[JdonFramework]--> getUploadFile session filter id=" + id, module);
    try {
      uploadFile = getUploadFileFromSession(request, id);
      if (uploadFile == null) {
        uploadFile = imageFilter.getUploadFile(request, id);
      }
    } catch (Exception ex) {
      Debug.logWarning(" getUploadFile error" + ex, module);

    }
    return uploadFile;
  }
444282
public function getUploadFieldOptions($field = null)
    {
        // get first option if no field provided
        if (is_null($field)) {
            $imagesFields = $this->getDefinedUploadFields();

            if (!$imagesFields) {
                throw new InvalidUploadFieldException(
                    'No upload fields are defined in $imageFields/$fileFields array on model.'
                );
            }

            $fieldKey = array_first(array_keys($imagesFields));
            $options = is_int($fieldKey) ? [] : array_first($imagesFields);

            return $options;
        }

        // check if provided filed defined
        if (!$this->hasImageField($field)) {
            throw new InvalidUploadFieldException(
                'Image/File field `' . $field . '` is not defined in $imageFields/$fileFields array on model.'
            );
        }

        return array_get($this->getDefinedUploadFields(), $field, []);
    }
337175
def param_upload(field, path):
    
    if not path:
        return None
    param = {}
    param['field'] = field
    param['path'] = path
    return param