getClientOriginalName example

/** @var UploadedFile $file */
            $file = $fileBag->get('plugin');
        } catch (Exception $e) {
            $this->View()->assign([
                'success' => false,
                'message' => $e->getMessage(),
            ]);

            return;
        }

        $information = pathinfo($file->getClientOriginalName());
        $extension = $information['extension'] ?? '';
        if ($extension !== 'zip') {
            $this->View()->assign([
                'success' => false,
                'message' => sprintf('Wrong archive extension %s. Zip archive expected', $extension),
            ]);
            unlink($file->getPathname());

            return;
        }

        

                ],
            ],
            ['url' => 'http://dunglas.fr'],
            ['custom' => $stdClass]
        );

        $symfonyRequest = $this->factory->createRequest($serverRequest);
        $files = $symfonyRequest->files->all();

        $this->assertEquals('http://les-tilleuls.coop', $symfonyRequest->query->get('url'));
        $this->assertEquals('doc1.txt', $files['doc1']->getClientOriginalName());
        $this->assertEquals('doc2.txt', $files['nested']['docs'][0]->getClientOriginalName());
        $this->assertEquals('doc3.txt', $files['nested']['docs'][1]->getClientOriginalName());
        $this->assertEquals('http://dunglas.fr', $symfonyRequest->request->get('url'));
        $this->assertEquals($stdClass$symfonyRequest->attributes->get('custom'));
        $this->assertEquals('Lille', $symfonyRequest->cookies->get('city'));
        $this->assertEquals('France', $symfonyRequest->server->get('country'));
        $this->assertEquals('The body', $symfonyRequest->getContent());
        $this->assertEquals('1.0', $symfonyRequest->headers->get('X-Dunglas-API-Platform'));
        $this->assertEquals(['a', 'b']$symfonyRequest->headers->all('X-data'));
    }

    

    protected function filterFiles(array $files): array
    {
        $filtered = [];
        foreach ($files as $key => $value) {
            if (\is_array($value)) {
                $filtered[$key] = $this->filterFiles($value);
            } elseif ($value instanceof UploadedFile) {
                if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) {
                    $filtered[$key] = new UploadedFile(
                        '',
                        $value->getClientOriginalName(),
                        $value->getClientMimeType(),
                        \UPLOAD_ERR_INI_SIZE,
                        true
                    );
                } else {
                    $filtered[$key] = new UploadedFile(
                        $value->getPathname(),
                        $value->getClientOriginalName(),
                        $value->getClientMimeType(),
                        $value->getError(),
                        true
                    );

  public function __construct(UploadedFile $uploadedFile) {
    $this->uploadedFile = $uploadedFile;
  }

  /** * {@inheritdoc} */
  public function getClientOriginalName(): string {
    return $this->uploadedFile->getClientOriginalName();
  }

  /** * {@inheritdoc} */
  public function isValid(): bool {
    return $this->uploadedFile->isValid();
  }

  /** * {@inheritdoc} */
\UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
            \UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
            \UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
            \UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
            \UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
        ];

        $errorCode = $this->error;
        $maxFilesize = \UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0;
        $message = $errors[$errorCode] ?? 'The file "%s" was not uploaded due to an unknown error.';

        return sprintf($message$this->getClientOriginalName()$maxFilesize);
    }
}
'message' => $e->getMessage(),
                'exception' => [
                    '_class' => \get_class($e),
                    'extension' => $extension,
                ],
            ]);

            return;
        }

        $filesystem = $this->container->get('shopware.filesystem.private');
        $destinationPath = $this->container->get(Shopware_Components_Config::class)->offsetGet('esdKey') . '/' . ltrim($file->getClientOriginalName(), '.');

        if ($overwriteMode === 'rename') {
            $counter = 1;
            do {
                $newFilename = pathinfo(ltrim($file->getClientOriginalName()), PATHINFO_FILENAME) . '-' . $counter . '.' . pathinfo($destinationPath, PATHINFO_EXTENSION);
                $destinationPath = $this->container->get(Shopware_Components_Config::class)->offsetGet('esdKey') . '/' . ltrim($newFilename, '.');
                ++$counter;
            } while ($filesystem->has($destinationPath));

            $this->View()->assign('newName', pathinfo($destinationPath, PATHINFO_BASENAME));
        }

        
$file = null;
        foreach ($files as $file) {
            $client->request('POST', '/', []['foo' => $file]);

            $files = $client->getRequest()->files->all();

            $this->assertCount(1, $files);

            $file = $files['foo'];

            $this->assertEquals('original', $file->getClientOriginalName());
            $this->assertEquals('mime/original', $file->getClientMimeType());
            $this->assertEquals(1, $file->getSize());
        }

        $file->move(\dirname($target)basename($target));

        $this->assertFileExists($target);
        unlink($target);
    }

    public function testUploadedFileWhenNoFileSelected()
    {
\UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
            \UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
            \UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
            \UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
            \UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
        ];

        $errorCode = $this->error;
        $maxFilesize = \UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0;
        $message = $errors[$errorCode] ?? 'The file "%s" was not uploaded due to an unknown error.';

        return sprintf($message$this->getClientOriginalName()$maxFilesize);
    }
}
if (!is_readable($path)) {
            $this->context->buildViolation($constraint->notReadableMessage)
                ->setParameter('{{ file }}', $this->formatValue($path))
                ->setCode(File::NOT_READABLE_ERROR)
                ->addViolation();

            return;
        }

        $sizeInBytes = filesize($path);
        $basename = $value instanceof UploadedFile ? $value->getClientOriginalName() : basename($path);

        if ($constraint->filenameMaxLength && $constraint->filenameMaxLength < $filenameLength = \strlen($basename)) {
            $this->context->buildViolation($constraint->filenameTooLongMessage)
                ->setParameter('{{ filename_max_length }}', $this->formatValue($constraint->filenameMaxLength))
                ->setCode(File::FILENAME_TOO_LONG)
                ->setPlural($constraint->filenameMaxLength)
                ->addViolation();

            return;
        }

        
if (!class_exists(AbstractPart::class)) {
            throw new \LogicException('You cannot pass non-empty bodies as the Mime component is not installed. Try running "composer require symfony/mime".');
        }

        if ($content = $request->getContent()) {
            return new TextPart($content, 'utf-8', 'plain', '8bit');
        }

        $fields = $request->request->all();
        foreach ($request->files->all() as $name => $file) {
            $fields[$name] = DataPart::fromPath($file->getPathname()$file->getClientOriginalName()$file->getClientMimeType());
        }

        return new FormDataPart($fields);
    }

    private function getHeaders(Request $request): array
    {
        $headers = [];
        foreach ($request->headers as $key => $value) {
            $headers[$key] = $value;
        }
        
private function setFileInfo()
    {
        if ($this->file === null) {
            return;
        }

        $extension = (string) $this->file->guessExtension();
        $name = $this->file->getBasename();

        if ($this->file instanceof UploadedFile) {
            // Load file information             $fileInfo = pathinfo($this->file->getClientOriginalName());
            $name = $fileInfo['filename'];

            if (isset($fileInfo['extension'])) {
                $extension = $fileInfo['extension'];
            }
        }

        $extension = strtolower($extension);

        // Validate extension         // #1 - whitelist

    public function uploadAction()
    {
        $file = Request::createFromGlobals()->files->get('emotionfile');
        $fileSystem = $this->container->get('file_system');

        if ($file->getClientMimeType() !== 'application/zip' && strtolower($file->getClientOriginalExtension()) !== 'zip') {
            $name = $file->getClientOriginalName();

            $fileSystem->remove($file->getPathname());

            $this->View()->assign([
                'success' => false,
                'message' => sprintf(
                    'Uploaded file %s is no zip file',
                    $name
                ),
            ]);

            

    private function createUploadedFile(UploadedFile $symfonyUploadedFile)
    {
        return $this->uploadedFileFactory->createUploadedFile(
            $this->streamFactory->createStreamFromFile(
                $symfonyUploadedFile->getRealPath()
            ),
            (int) $symfonyUploadedFile->getSize(),
            $symfonyUploadedFile->getError(),
            $symfonyUploadedFile->getClientOriginalName(),
            $symfonyUploadedFile->getClientMimeType()
        );
    }

    /** * {@inheritdoc} */
    public function createResponse(Response $symfonyResponse)
    {
        $response = $this->responseFactory->createResponse($symfonyResponse->getStatusCode(), Response::$statusTexts[$symfonyResponse->getStatusCode()] ?? '');

        


    public function testGetClientOriginalName()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            null
        );

        $this->assertEquals('original.gif', $file->getClientOriginalName());
    }

    public function testGetClientOriginalExtension()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            null
        );

        
$profileEntity = $this->findProfile($context$profileId);

        if (!\in_array($profileEntity->getType()[ImportExportProfileEntity::TYPE_IMPORT, ImportExportProfileEntity::TYPE_IMPORT_EXPORT], true)) {
            throw new ProfileWrongTypeException($profileEntity->getId()$profileEntity->getType());
        }

        $type = $this->fileService->detectType($file);
        if ($type !== $profileEntity->getFileType()) {
            throw new UnexpectedFileTypeException($file->getClientMimeType()$profileEntity->getFileType());
        }

        $fileEntity = $this->fileService->storeFile($context$expireDate$file->getPathname()$file->getClientOriginalName(), ImportExportLogEntity::ACTIVITY_IMPORT);
        $activity = $dryRun ? ImportExportLogEntity::ACTIVITY_DRYRUN : ImportExportLogEntity::ACTIVITY_IMPORT;

        return $this->createLog($context$activity$fileEntity$profileEntity$config);
    }

    public function cancel(Context $context, string $logId): void
    {
        $logEntity = $this->findLog($context$logId);

        if ($logEntity === null) {
            throw new ProcessingException('LogEntity not found');
        }
Home | Imprint | This part of the site doesn't use cookies.