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.
一個錯誤的文件名不帶擴展,爲什麼?在移動到結束路徑之前或之後重命名文件的正確方法是什麼?有什麼建議?
只有一件事,我不知道爲什麼會發生:'警告:fclose():78是不是一個有效的流資源'否則工程完美 – ReynierPM
奇怪,因爲'fopen'返回一個成功的資源和'FALSE' on失敗。也許該文件已經關閉,所以PHP觸發警告? – giosh94mhz
另請注意,symfony的'File'是'SplFileInfo'的子類型,所以可以使用'$ avatarFile-> openFile('r')'....我會更新我的答案以向您展示「正確」的方式 – giosh94mhz