persistFileToMedia example

$this->mediaRepository->create(
            [
                [
                    'id' => $mediaId,
                ],
            ],
            $context
        );

        try {
            $this->fileSaver->persistFileToMedia(
                $mediaFile,
                'test-file',
                $mediaId,
                $context
            );
        } finally {
            if (file_exists($tempFile)) {
                unlink($tempFile);
            }
        }

        


        $fileName = $request->query->getString('fileName', $mediaId);
        $destination = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $fileName);

        if (!\is_string($destination)) {
            throw MediaException::illegalFileName($fileName, 'Filename must be a string');
        }

        try {
            $uploadedFile = $this->mediaService->fetchFile($request$tempFile);
            $this->fileSaver->persistFileToMedia(
                $uploadedFile,
                $destination,
                $mediaId,
                $context
            );

            $this->eventDispatcher->dispatch(new MediaUploadedEvent($mediaId$context));
        } finally {
            unlink($tempFile);
        }

        
MediaFile $mediaFile,
        string $filename,
        Context $context,
        ?string $folder = null,
        ?string $mediaId = null,
        bool $private = true
    ): string {
        if (!$mediaId) {
            $mediaId = $this->createMediaInFolder($folder ?? '', $context$private);
        }

        $this->fileSaver->persistFileToMedia($mediaFile$filename$mediaId$context);

        return $mediaId;
    }

    public function saveFile(
        string $blob,
        string $extension,
        string $contentType,
        string $filename,
        Context $context,
        ?string $folder = null,
        ?
$mediaRepository = $this->getContainer()->get('media.repository');
        $mediaRepository->create(
            [
                [
                    'id' => $mediaId,
                ],
            ],
            $context
        );

        try {
            $this->getContainer()->get(FileSaver::class)->persistFileToMedia(
                $mediaFile,
                'test-file',
                $mediaId,
                $context
            );
        } finally {
            if (file_exists($tempFile)) {
                unlink($tempFile);
            }
        }

        
$mediaFile = new MediaFile(
            $file->getPathname(),
            $file->getMimeType() ?? '',
            $file->getClientOriginalExtension(),
            $file->getSize() ?: 0
        );

        $mediaId = $this->mediaService->createMediaInFolder($folder$context$isPrivate);

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($mediaFile$mediaId): void {
            $this->fileSaver->persistFileToMedia(
                $mediaFile,
                pathinfo(Uuid::randomHex(), \PATHINFO_FILENAME),
                $mediaId,
                $context
            );
        });

        return $mediaId;
    }

    private function checkValidFile(UploadedFile $file): void
    {
$mediaFiles = $this->cacheMediaFiles;
        // prevent recursion         $this->cacheMediaFiles = [];

        foreach ($event->getIds() as $id) {
            if (!isset($mediaFiles[$id])) {
                continue;
            }
            $mediaFile = $mediaFiles[$id];

            $this->fileSaver->persistFileToMedia(
                $mediaFile['media'],
                $mediaFile['destination'],
                $id,
                $event->getContext()
            );
        }
    }

    public function reset(): void
    {
        $this->cacheMediaFiles = [];
    }
$mediaSearchResult->method('get')->willReturn($currentMedia);
        $mediaSearchResult->method('getEntities')->willReturn($mediaWithRelatedFileName);
        $this->mediaRepository->method('search')->willReturn($mediaSearchResult);

        $mediaFile = new MediaFile('foo', 'image/png', 'png', 0);

        $context = Context::createDefaultContext(new AdminApiSource(Uuid::randomHex()));

        static::expectException(MediaException::class);
        static::expectExceptionMessage('A file with the name "foo.png" already exists.');

        $this->fileSaver->persistFileToMedia($mediaFile, 'foo', Uuid::randomHex()$context);
    }

    public static function duplicateFileNameProvider(): \Generator
    {
        yield 'new private file exists as private in database / different filesystems' => [
            true,
        ];

        yield 'new public file exists as public in database / different filesystems' => [
            false,
        ];
    }
$this->mediaRepository = $this->getContainer()->get('media.repository');
    }

    public function testLoadMediaFile(): void
    {
        $context = Context::createDefaultContext();
        $blob = \file_get_contents(self::TEST_IMAGE);
        static::assertIsString($blob);
        $mediaFile = $this->fileFetcher->fetchBlob($blob, 'png', 'image/png');
        $mediaId = Uuid::randomHex();
        $this->mediaRepository->create([['id' => $mediaId]]$context);
        $this->fileSaver->persistFileToMedia($mediaFile$mediaId . '.png', $mediaId$context);

        static::assertSame($blob$this->fileLoader->loadMediaFile($mediaId$context));

        $this->mediaRepository->delete([['id' => $mediaId]]$context);
    }

    public function testLoadMediaFileStream(): void
    {
        $context = Context::createDefaultContext();
        $blob = \file_get_contents(self::TEST_IMAGE);
        static::assertIsString($blob);
        

                        'id' => $mediaId,
                        'title' => "File #{$i}: {$file}",
                        'mediaFolderId' => $isDownloadFile ? $downloadFolderId : $mediaFolderId,
                        'private' => $isDownloadFile,
                        'tags' => $this->getTags($tags),
                    ],
                ],
                $writeContext
            );

            $this->mediaUpdater->persistFileToMedia(
                new MediaFile(
                    $file,
                    (string) mime_content_type($file),
                    pathinfo($file, \PATHINFO_EXTENSION),
                    (int) filesize($file)
                ),
                $this->fileNameProvider->provide(
                    pathinfo($file, \PATHINFO_FILENAME),
                    pathinfo($file, \PATHINFO_EXTENSION),
                    $mediaId,
                    $context->getContext()
                ),
if (!empty($media)) {
            $mediaIds = array_column($media, 'media');

            $this->mediaRepository->create($mediaIds$context);

            foreach ($media as $item) {
                if (!$item['mediaFile'] instanceof MediaFile) {
                    throw MediaException::missingFile($item['media']['id']);
                }

                try {
                    $this->fileSaver->persistFileToMedia($item['mediaFile']$item['basename']$item['media']['id']$context);
                } catch (MediaException $e) {
                    if ($e->getErrorCode() !== MediaException::MEDIA_DUPLICATED_FILE_NAME) {
                        throw $e;
                    }

                    $newFileName = $this->fileNameProvider->provide(
                        $item['basename'],
                        $item['mediaFile']->getFileExtension(),
                        null,
                        $context
                    );
                    
 $downloadFiles))
                ->build();
        }

        $this->salesChannelContext->getContext()->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($products): void {
            $this->productRepository->create($products$context);
            $downloads = array_merge(...array_column($products, 'downloads'));

            foreach ($downloads as $download) {
                $media = $download['media'];
                $mediaFile = $this->fileFetcher->fetchBlob($media['id']$media['fileExtension'], '');
                $this->fileSaver->persistFileToMedia($mediaFile$media['fileName']$media['id']$context);
            }
        });

        foreach ($ids->prefixed('product-') as $id) {
            $cart = $this->addProduct($id, 1, $cart$this->cartService, $this->salesChannelContext);
        }

        return $cart;
    }

    private function changeTransactionStateToPaid(string $orderId): void
    {
Home | Imprint | This part of the site doesn't use cookies.