Typo3 下载远程文件并创建文件对象

Typo3 download remote files and create a file object

如何在 Typo3 v10 中将远程文件保存到本地存储。

有以下代码,没有文件被保存在 fileadmin 存储中

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);
    }

在 typo3 中保存远程文件并创建 fileObject 的正确方法是什么?

TYPO3 具有 API 通过文件抽象层 (FAL) 获取或添加文件的功能。

此示例在默认存储的根文件夹中添加一个新文件:

$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'
);

详情请参考documentation