Home > Net >  Typo3 download remote files and create a file object
Typo3 download remote files and create a file object

Time:02-12

How do I save a remote file to local storage in Typo3 v10.

Having the following code, no files are getting saved in fileadmin storage

private function saveFileFromUri($fileUrl)
    {
        $urlParts = parse_url($fileUrl);
        $pathParts = pathinfo($urlParts['path']);
        $fileName = $pathParts['basename'];

        $file = GeneralUtility::getUrl($fileUrl);
        $temporaryFile = GeneralUtility::tempnam('temp/' . $fileName);
        $storage = $this->defaultStorage->createFolder($pathParts['dirname']);

        if ($file === false) {
            $error = sprintf(
                'File %s could not be fetched.',
                $fileUrl
            );
            if (isset($report['message'])) {
                $error .= ' ' . sprintf(
                    'Reason: %s (code: %s)',
                    $report['message'],
                    $report['error'] ?? 0
                );
            }
            throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
                $error,
                1613555057
            );
        }
        \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($file);

        GeneralUtility::writeFileToTypo3tempDir(
            $temporaryFile,
            $file
        );

        $fileObject = $storage->addFile(
            $temporaryFile,
            $storage,
            $fileName
        );

        \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($fileObject);
    }

What is the right way to save remote files in typo3 and create a fileObject?

CodePudding user response:

TYPO3 has an API to get or add files via the File Abstraction Layer (FAL).

This example adds a new file in the root folder of the default storage:

$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
$storage = $storageRepository->getDefaultStorage();
$newFile = $storage->addFile(
      '/tmp/temporary_file_name.ext',
      $storage->getRootLevelFolder(),
      'final_file_name.ext'
);

Please refer to the documentation for details.

  • Related