无法在 UploadedFile Symfony 上获取文件内容

iam*_*015 5 symfony

我有以下函数定义:

public function save(UploadedFile $file, string $fileSystemName)
{
    $fs = $this->fileSystemMap->get($fileSystemName);

    $contents = file_get_contents($file->getRealPath());
    $filename = sprintf('%s/%s/%s/%s.%s', date('Y'), date('m'), date('d'), uniqid(), $file->getClientOriginalExtension());

    $fs->write($fileName, $contents);
}
Run Code Online (Sandbox Code Playgroud)

代码运行时:

file_get_contents($file->getRealPath());

它抛出一个错误说:

警告:file_get_contents(/tmp/phpM9Ckmq):无法打开流:没有那个文件或目录

请注意,我也尝试使用 $file->getPathName(),但结果是一样的。

为什么会这样?

谢谢!

Mic*_*ł G 9

读取上传文件内容的最简单方法是:

  public function index(Request $request)
{  $raw='';

    if ($request->getMethod() == "POST") {
        $files = $request->files->all();
        foreach ($files as $file) {
            if ($file instanceof UploadedFile) {
                $raw .= file_get_contents($file->getPathname());

            }
        }

    }

    return $this->render('main/index.html.twig', [
        'controller_name' => 'MainController',
    ]);
}
Run Code Online (Sandbox Code Playgroud)

您的数据将存储在 $raw


小智 -1

您可以在 UploadFormType 中使用 Symfony\Component\Form\Extension\Core\Type\FileType 作为文件

就像是:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('file', UploadFormType::class);
}
Run Code Online (Sandbox Code Playgroud)

之后你可以在控制器中执行类似的操作

$form = $this->get('form.factory')->create(UploadFormType::class);
$form->handleRequest($request);

$file = $form->getData();
Run Code Online (Sandbox Code Playgroud)

$file 将是 \SplFileInfo 的实例,您可以使用 $file->getRealPath() 方法。