【问题标题】:Get file extension after file is uploaded and moved in Symfony2在 Symfony2 中上传和移动文件后获取文件扩展名
【发布时间】:2015-05-29 14:11:06
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    由于你moved 和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());
    

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

    【讨论】:

    • 只有一件事我不知道为什么会发生:Warning: fclose(): 78 is not a valid stream resource 否则效果很好
    • 奇怪,因为fopen 成功返回资源,FALSE 失败。可能文件已经关闭,所以php触发警告?
    • 另请注意,symfony FileSplFileInfo 的子类型,所以可以使用 $avatarFile->openFile('r')...。我会更新我的答案以向您展示“正确”的方式跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多