在 Symfony2 中上传和移动文件后获取文件扩展名

Get file extension after file is uploaded and moved in Symfony2

我正在通过 Symfony2 上传一个文件,我正在尝试重命名原始文件以避免覆盖同一个文件。这就是我正在做的:

$uploadedFile = $request->files;
$uploadPath = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/';

try {
    $uploadedFile->get('avatar')->move($uploadPath, $uploadedFile->get('avatar')->getClientOriginalName());
} catch (\ Exception $e) {
    // set error 'can not upload avatar file'
}

// this get right filename
$avatarName = $uploadedFile->get('avatar')->getClientOriginalName();
// this get wrong extension meaning empty, why? 
$avatarExt = $uploadedFile->get('avatar')->getExtension();

$resource = fopen($uploadPath . $uploadedFile->get('avatar')->getClientOriginalName(), 'r');
unlink($uploadPath . $uploadedFile->get('avatar')->getClientOriginalName());

我正在重命名文件如下:

$avatarName = sptrinf("%s.%s", uniqid(), $uploadedFile->get('avatar')->getExtension());

但是 $uploadedFile->get('avatar')->getExtension() 没有给我上传文件的扩展名,所以我给了一个错误的文件名,比如没有扩展名的 jdsfhnhjsdf.,为什么?在移动到结束路径之后或之前重命名文件的正确方法是什么?有什么建议吗?

嗯,如果你知道的话,解决方案真的很简单。

由于您 moved UploadedFile,不能再使用当前对象实例。该文件不再存在,因此 getExtension 将在 null 中 return。新文件实例是 return 从 move.

编辑的

将您的代码更改为(为清楚起见重构):

    $uploadPath = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/';

    try {
        $uploadedAvatarFile = $request->files->get('avatar');

        /* @var $avatarFile \Symfony\Component\HttpFoundation\File\File */
        $avatarFile = $uploadedAvatarFile->move($uploadPath, $uploadedAvatarFile->getClientOriginalName());

        unset($uploadedAvatarFile);
    } catch (\Exception $e) {
        /* if you don't set $avatarFile to a default file here
         * you cannot execute the next instruction.
         */
    }

    $avatarName = $avatarFile->getBasename();
    $avatarExt = $avatarFile->getExtension();

    $openFile = $avatarFile->openFile('r');
    while (! $openFile->eof()) {
        $line = $openFile->fgets();
        // do something here...
    }
    // close the file
    unset($openFile);
    unlink($avatarFile->getRealPath());

(代码未经测试,只是写的)希望对您有所帮助!