@throws UserMessageException

$return \Symfony\Component\HttpFoundation\File\UploadedFile
341941
private function getPostedFile()
    {
        $file = $this->request->files->get('file');
        if ($file === null) {
            throw new UserMessageException(t('Please specify the file to be analyzed'));
        }
        if (!$file->isValid()) {
            throw new UserMessageException($file->getErrorMessage());
        }
        if ($this->maxFileSize) {
            $filesize = @filesize($file->getPathname());
            if ($filesize !== false && $filesize > $this->maxFileSize) {
                throw new UserMessageException(t('The uploaded file is too big'));
            }
        }

        return $file;
    }
824502
private function uploadOne(UploadedFile $file)
    {
        try {
            $validator = new FileValidator([$this->_config]);
            if ($validator->validate($file, $error)) {
                $fileInfo = $file->save();
                $result = [
                    'name' => Html::encode($fileInfo->filename),
                    'url' => $fileInfo->getUrl(),
                    'path' => $fileInfo->path,
                    'extension' => $file->extension,
                    'type' => $fileInfo->type,
                    'size' => $fileInfo->size
                ];
                if ($this->onlyImage !== true) {
                    $result['filename'] = $result['name'];
                }
            } else {
                $result = [
                    'error' => $error
                ];
            }
        } catch (Exception $e) {
            $result = [
                'error' => $e->getMessage()
            ];
        }
        return $result;
    }
885256
private function uploadFile(UploadedFile $file)
    {
        /** @var FileStorage $fileStorage */
        $fileStorage = Yii::$app->get('fileStorage');

        $filename = $fileStorage->saveUploadedFile($file);

        return $fileStorage->put($filename, $file->name);
    }
838202
public function run()
    {
        $model = new ImportForm();

        if (Yii::$app->request->isPost) {
            $model->importFile = UploadedFile::getInstance($model, 'importFile');

            if ($model->validate()) {
                try {
                    $result = $model->import();

                    $message = Yii::t('language', 'Successfully imported {fileName}', ['fileName' => $model->importFile->name]);
                    $message .= "<br/>\n";
                    foreach ($result as $type => $typeResult) {
                        $message .= "<br/>\n" . Yii::t('language', '{type}: {new} new, {updated} updated', [
                            'type' => $type,
                            'new' => $typeResult['new'],
                            'updated' => $typeResult['updated'],
                        ]);
                    }

                    $languageIds = Language::find()
                        ->select('language_id')
                        ->where(['status' => Language::STATUS_ACTIVE])
                        ->column();

                    foreach ($languageIds as $languageId) {
                        $generator = new Generator($this->controller->module, $languageId);
                        $generator->run();
                    }

                    Yii::$app->getSession()->setFlash('success', $message);
                } catch (\Exception $e) {
                    if (YII_DEBUG) {
                        throw $e;
                    } else {
                        Yii::$app->getSession()->setFlash('danger', str_replace("\n", "<br/>\n", $e->getMessage()));
                    }
                }
            }
        }

        return $this->controller->render('import', [
            'model' => $model,
        ]);
    }
275589
public function newUpload()
    {
        if (null === $this->getFile()) {
            return null;
        }

        $this->moveFile();

        return $this->getUploadRootDir() . $this->path;
    }
1084581
protected function loadMessages()
    {
        $messageText = $this->event->get('text');

        $user_id = $this->event->get('user');
        if (is_array($user_id)) {
            $user_id = $user_id['id'];
        }

        $channel_id = $this->event->get('channel');
        if (is_array($channel_id)) {
            $channel_id = $channel_id['id'];
        }
        if ($this->event->get('subtype') === 'file_share') {
            $file = Collection::make($this->event->get('file'));

            if (strstr($file->get('mimetype'), 'image')) {
                $message = new IncomingMessage(Image::PATTERN, $user_id, $channel_id, $this->event);
                $message->setIsFromBot($this->isBot());
                $message->setImages([new Image($file->get('permalink'), $file)]);
            } elseif (strstr($file->get('mimetype'), 'audio')) {
                $message = new IncomingMessage(Audio::PATTERN, $user_id, $channel_id, $this->event);
                $message->setIsFromBot($this->isBot());
                $message->setAudio([new Audio($file->get('permalink'), $file)]);
            } elseif (strstr($file->get('mimetype'), 'video')) {
                $message = new IncomingMessage(Video::PATTERN, $user_id, $channel_id, $this->event);
                $message->setIsFromBot($this->isBot());
                $message->setVideos([new Video($file->get('permalink'), $file)]);
            } else {
                $message = new IncomingMessage(\BotMan\BotMan\Messages\Attachments\File::PATTERN, $user_id, $channel_id, $this->event);
                $message->setIsFromBot($this->isBot());
                $message->setFiles([new \BotMan\BotMan\Messages\Attachments\File($file->get('permalink'), $file)]);
            }

            return [$message];
        }

        $message = new IncomingMessage($messageText, $user_id, $channel_id, $this->event);
        $message->setIsFromBot($this->isBot());

        $this->messages = [$message];
    }
371355
public function upload()
	{
		$response = array('uploaded' => false);

		foreach ((array)$_FILES as $file) {
			$targetFolder = isset($_POST['folder']) ? $_POST['folder'] : '/';
			$response = array_merge($response, $this->uploadFile($file, $targetFolder . '/'));
		}
        $this->returnJson($response);
	}
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);
    }
61023
public function getFileContent()
    {
        $file = $this->getAttribute('file');
        if (empty($file) && !$this->getIsNewRecord()) {
            $file = $this->refreshFile();
        }

        if (empty($file)) {
            return null;
        } elseif ($file instanceof Download) {
            $fileSize = $file->getSize();
            return empty($fileSize) ? null : $file->toString();
        } elseif ($file instanceof UploadedFile) {
            return file_get_contents($file->tempName);
        } elseif (is_string($file)) {
            if (file_exists($file)) {
                return file_get_contents($file);
            }
            throw new InvalidParamException("File '{$file}' does not exist.");
        }

        throw new InvalidParamException('Unsupported type of "file" attribute.');
    }
71394
public function validate() {
		if( $this->error ) {
			switch( $this->error ) {
				case UPLOAD_ERR_INI_SIZE:
				case UPLOAD_ERR_FORM_SIZE: {
					throw new UserException('fileTooBig');
					break;
				}
				case UPLOAD_ERR_PARTIAL:
				case UPLOAD_ERR_NO_FILE: {
					throw new UserException('transfertIssue');
					break;
				}
				default: {
					// UPLOAD_ERR_NO_TMP_DIR UPLOAD_ERR_CANT_WRITE UPLOAD_ERR_EXTENSION
					// http://php.net/manual/fr/features.file-upload.errors.php
					log_error("Server upload error (error={$this->error}, name={$this->fileName})", 'Uploading file', false);
					throw new UserException('serverIssue');
				}
			}
		}
		
		if( $this->expectedType !== NULL ) {
			if( $this->getType() !== $this->expectedType ) {
				throw new UserException('invalidType');
			}
		}
		if( $this->allowedExtensions !== NULL ) {
			$ext = $this->getExtension();
			if( $ext === $this->allowedExtensions || (is_array($this->allowedExtensions) && !in_array($ext, $this->allowedExtensions)) ) {
				throw new UserException('invalidExtension');
			}
		}
		if( $this->allowedMimeTypes !== NULL) {
			$mt = $this->getMIMEType();
			if( $mt === $this->allowedMimeTypes || (is_array($this->allowedMimeTypes) && !in_array($mt, $this->allowedMimeTypes)) ) {
				throw new UserException('invalidMimeType');	
			}
		}
	}
394122
public function extract()
    {
        if ($this->extractedWorkDir !== null) {
            return;
        }
        if (!is_file($this->packageArchive)) {
            throw new UserMessageException(t('Archive not found: %s', $this->packageArchive));
        }
        try {
            $workDir = $this->getVolatileDirectory()->getPath();
            try {
                $this->app->make('helper/zip')->unzip($this->packageArchive, $workDir);
            } catch (\Exception $x) {
                throw new UserMessageException($x->getMessage());
            }
            $fs = $this->getVolatileDirectory()->getFilesystem();
            $dirs = array_filter($fs->directories($workDir), function ($dn) {
                return strpos(basename($dn), '.') !== 0;
            });
            if (count($dirs) === 1) {
                $someFile = false;
                foreach ($fs->files($workDir) as $fn) {
                    if (strpos(basename($fn), '.') !== 0) {
                        $someFile = true;
                        break;
                    }
                }
                if ($someFile === false) {
                    $workDir = $dirs[0];
                }
            }
        } catch (\Exception $x) {
            $this->volatileDirectory = null;
            throw $x;
        }
        $this->extractedWorkDir = $workDir;
    }
672521
public function store(UploadedFileSource $file, $folderId, $userId, $originalFileId, $useWizard)
    {
        $tempId = uniqid();
        $tempDir = $this->tempDir.'/'.$tempId.'/';
        $tempName = $tempDir.basename($file->getPath());

        if (!file_exists($tempDir) && !mkdir($tempDir, 0777, true)) {
            throw new StoreUploadedFileException('Error occured while creating temp upload folder.');
        }

        if (!move_uploaded_file($file->getPath(), $tempName)) {
            throw new StoreUploadedFileException('Error occured during uploaded file move.');
        }

        $tempFile = new TempFile(
            $tempId,
            $file->getName(),
            $tempName,
            $file->getMimeType(),
            $file->getSize(),
            $this->hasher->fromPath($tempName),
            $originalFileId,
            $folderId,
            $userId,
            $useWizard
        );

        /*
        $event = new BeforeStoreUploadEvent($this, $tempFile);
        if ($this->dispatcher->dispatch(MediaSiteEvents::BEFORE_STORE_UPLOAD, $event)->isPropagationStopped()) {
            return null;
        }
        */

        $tempFiles = $this->session->get('mediamanager.temp_files');
        $tempFiles[$tempId] = $tempFile;
        $this->session->set('mediamanager.temp_files', $tempFiles);

        /*
        $event = new StoreUploadEvent($this, $tempFile);
        $this->dispatcher->dispatch(MediaSiteEvents::STORE_UPLOAD, $event);
        */

        return $tempFile;
    }
1348543
public function saveFile(UploadedFile $file)
    {
        Validator::validate(
            [$this->getName() => $file],
            $this->getUploadValidationRules(),
            $this->getUploadValidationMessages(),
            $this->getUploadValidationTitles()
        );

        $path = $file->storeAs(
            $this->getUploadPath($file),
            $this->getUploadFileName($file),
            $this->getDisk()
        );

        return $this->getFileInfo($path);
    }
131641
private function prepareUpload() {
		if(!current_user_can('upload_files')) {
			json_response(["status" => "error", "message" => "Current user can't upload."]);
		}

		if (!$this->client || !$this->client->enabled()) {
			json_response(["status" => "error", "message" => "Storage settings are invalid."]);
		}

		$filename = $_POST['filename'];
		$type = $_POST['type'];

		if (empty($filename) || empty($type)) {
			json_response(["status" => "error", "message" => "Invalid file name or missing type."]);
		}

		$prefix = StorageSettings::prefix(null);
		$parts = explode('/', $filename);
		$bucketFilename = array_pop($parts);

		$uploadInfo = $this->client->uploadUrl($prefix.$bucketFilename,StorageSettings::privacy(), $type,StorageSettings::cacheControl(), StorageSettings::expires());
		$res = $uploadInfo->toArray();
		$res['status'] = 'ready';
		json_response($res);
	}
60385
public function saveUploadedFiles()
    {
        try
        {
            if(($xUploadPlugin = $this->getPluginManager()->getRequestPlugin(self::FILE_UPLOAD)) == null)
            {
                throw new Exception($this->trans('errors.upload.plugin'));
            }
            elseif(!$xUploadPlugin->canProcessRequest())
            {
                throw new Exception($this->trans('errors.upload.request'));
            }
            // Save uploaded files
            $sKey = $xUploadPlugin->saveUploadedFiles();
            $sResponse = '{"code": "success", "upl": "' . $sKey . '"}';
            $return = true;
        }
        catch(Exception $e)
        {
            $sResponse = '{"code": "error", "msg": "' . addslashes($e->getMessage()) . '"}';
            $return = false;
        }
        // Send the response back to the browser
        echo '<script>var res = ', $sResponse, '; </script>';
        if(($this->getOption('core.process.exit')))
        {
            exit();
        }
        return $return;
    }
255690
public static function findUploadedFileFactory()
    {
        try {
            $messageFactory = static::findOneByType(UploadedFileFactoryInterface::class);
        } catch (DiscoveryFailedException $e) {
            throw self::createException('uploaded file factory', $e);
        }

        return static::instantiateClass($messageFactory);
    }
711698
public function upload()
    {
        $uploaded_files = request()->file('upload');
        $error_bag = [];
        $new_filename = null;

        foreach (is_array($uploaded_files) ? $uploaded_files : [$uploaded_files] as $file) {
            try {
                $new_filename = $this->lfm->upload($file);
            } catch (\Exception $e) {
                Log::error($e->getMessage(), [
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'trace' => $e->getTraceAsString()
                ]);
                array_push($error_bag, $e->getMessage());
            }
        }

        if (is_array($uploaded_files)) {
            $response = count($error_bag) > 0 ? $error_bag : parent::$success_response;
        } else { // upload via ckeditor 'Upload' tab
            if (is_null($new_filename)) {
                $response = $error_bag[0];
            } else {
                $response = view(Lfm::PACKAGE_NAME . '::use')
                    ->withFile($this->lfm->setName($new_filename)->url());
            }
        }

        return $response;
    }