2015-05-29 72 views
1

我正在通過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.一個錯誤的文件名不帶擴展,爲什麼?在移動到結束路徑之前或之後重命名文件的正確方法是什麼?有什麼建議?

回答

4

那麼,如果你知道它的解決方案非常簡單。

由於您move d 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()); 

(代碼沒有測試,只是寫的)希望它可以幫助!

+0

只有一件事,我不知道爲什麼會發生:'警告:fclose():78是不是一個有效的流資源'否則工程完美 – ReynierPM

+0

奇怪,因爲'fopen'返回一個成功的資源和'FALSE' on失敗。也許該文件已經關閉,所以PHP觸發警告? – giosh94mhz

+0

另請注意,symfony的'File'是'SplFileInfo'的子類型,所以可以使用'$ avatarFile-> openFile('r')'....我會更新我的答案以向您展示「正確」的方式 – giosh94mhz

相關問題