1

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

4

1 回答 1

4

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

由于您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());

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

于 2015-05-29T14:44:39.600 回答