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

时间:2015-05-29 14:11:07

标签: php symfony symfony-2.6 symfony-http-foundation

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

SELECT t1.*, t2.donor_name,t2.ID, t3.ID,t3.item_name, t4.store_name, t4.ID
FROM donated_items as t1
LEFT JOIN donor_detail  as t2 ON t1.donor_id = t2.ID
LEFT JOIN items  as t3 ON t1.item_id = t3.ID
LEFT JOIN stores  as t4 ON t1.store_id = t4.ID

我正在重命名文件如下:

$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()没有扩展名,为什么?在移动到结束路径之后或之前重命名文件的正确方法是什么?有什么建议吗?

1 个答案:

答案 0 :(得分:4)

如果你知道的话,解决方案非常简单。

由于您move UploadedFile,因此无法再使用当前对象实例。该文件已不存在,因此getExtension将在null中返回。新文件实例从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());

(代码未经测试,只是写了)希望它有所帮助!

相关问题