getClientMimeType example

array $config = [],
        bool $dryRun = false
    ): ImportExportLogEntity {
        $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 (!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;
        }
        


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

        $this->assertEquals('application/octet-stream', $file->getClientMimeType());

        if (\extension_loaded('fileinfo')) {
            $this->assertEquals('image/gif', $file->getMimeType());
        }
    }

    public function testFileUploadsWithUnknownMimeType()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/.unknownextension',
            'original.gif',
            

    public function guessClientExtension(): ?string
    {
        if (!class_exists(MimeTypes::class)) {
            throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
        }

        return MimeTypes::getDefault()->getExtensions($this->getClientMimeType())[0] ?? null;
    }

    /** * Returns the upload error. * * If the upload was successful, the constant UPLOAD_ERR_OK is returned. * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. */
    public function getError(): int
    {
        return $this->error;
    }
$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()
    {
        
// use custom name if provided             if (!empty($params['name'])) {
                // Use the provided name to overwrite the file name, but keep the extensions to allow                 // automatic detection of the file type                 $fileName = $params['name'] . '.' . $fileExtension;
            }

            $params['name'] = $this->resource->getUniqueFileName($file->getPathname()$fileName);
            $params['file'] = new UploadedFile(
                $file->getPathname(),
                $params['name'],
                $file->getClientMimeType(),
                $file->getError()
            );
        }

        return $params;
    }

    /** * Use the ID of the authenticated user as a fallback 'userId' */
    private function prepareFallbackUser(array $params): array
    {

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

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

        if ($symfonyResponse instanceof BinaryFileResponse && !$symfonyResponse->headers->has('Content-Range')) {
            $stream = $this->streamFactory->createStreamFromFile(
                $symfonyResponse->getFile()->getPathname()
            );
        }
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 guessClientExtension(): ?string
    {
        if (!class_exists(MimeTypes::class)) {
            throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
        }

        return MimeTypes::getDefault()->getExtensions($this->getClientMimeType())[0] ?? null;
    }

    /** * Returns the upload error. * * If the upload was successful, the constant UPLOAD_ERR_OK is returned. * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. */
    public function getError(): int
    {
        return $this->error;
    }
return $fileEntity;
    }

    public function detectType(UploadedFile $file): string
    {
        // TODO: we should do a mime type detection on the file content         $guessedExtension = $file->guessClientExtension();
        if ($guessedExtension === 'csv' || $file->getClientOriginalExtension() === 'csv') {
            return 'text/csv';
        }

        return $file->getClientMimeType();
    }

    public function getWriter(): AbstractWriter
    {
        return $this->writer;
    }

    public function generateFilename(ImportExportProfileEntity $profile): string
    {
        $extension = $profile->getFileType() === 'text/xml' ? 'xml' : 'csv';
        $timestamp = date('Ymd-His');

        
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;
        }
        
$uploadedFile = $this->createUploadedFile('An uploaded file.', \UPLOAD_ERR_OK, 'myfile.txt', 'text/plain');
        $symfonyUploadedFile = $this->callCreateUploadedFile($uploadedFile);
        $size = $symfonyUploadedFile->getSize();

        $uniqid = uniqid();
        $symfonyUploadedFile->move($this->tmpDir, $uniqid);

        $this->assertEquals($uploadedFile->getSize()$size);
        $this->assertEquals(\UPLOAD_ERR_OK, $symfonyUploadedFile->getError());
        $this->assertEquals('myfile.txt', $symfonyUploadedFile->getClientOriginalName());
        $this->assertEquals('txt', $symfonyUploadedFile->getClientOriginalExtension());
        $this->assertEquals('text/plain', $symfonyUploadedFile->getClientMimeType());
        $this->assertEquals('An uploaded file.', file_get_contents($this->tmpDir.'/'.$uniqid));
    }

    public function testCreateUploadedFileWithError()
    {
        $this->expectException(FileException::class);
        $this->expectExceptionMessage('The file "e" could not be written on disk.');

        $uploadedFile = $this->createUploadedFile('Error.', \UPLOAD_ERR_CANT_WRITE, 'e', 'text/plain');
        $symfonyUploadedFile = $this->callCreateUploadedFile($uploadedFile);

        

    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()] ?? '');

        if ($symfonyResponse instanceof BinaryFileResponse && !$symfonyResponse->headers->has('Content-Range')) {
            


    public function getMappingFromTemplate(
        Context $context,
        UploadedFile $file,
        string $sourceEntity,
        string $delimiter = ';',
        string $enclosure = '"',
        string $escape = '\\'
    ): MappingCollection {
        if ($this->fileService->detectType($file) !== 'text/csv') {
            throw new UnexpectedFileTypeException($file->getClientMimeType(), 'text/csv');
        }

        if ($file->getSize() < 1) {
            throw new FileEmptyException($file->getFilename());
        }

        $filePath = $file->getRealPath();
        if (!$filePath) {
            throw new \RuntimeException('File does not exists');
        }

        
Home | Imprint | This part of the site doesn't use cookies.