I'm having a problem getting extension for uploaded XML files. Tried getExtension()
(returns empty string), guessExtension()
and guessClientExtension()
(both returns NULL
).
Should I just hardcode extension (I know it should always be XML) or is there a way to get it? I see mimeType of the uploaded file is text/xml
. When I upload .txt file, it gets extension right.
Maybe I'm getting uploaded file wrong?
$request = $this->getRequest();
$form = $this->createForm(new FileImportType(), null, ['em' => $this->getDoctrine()->getManager()]);
$form->submit($request);
if ($form->isValid()) {
$file = null; // @var $file \Symfony\Component\HttpFoundation\File\UploadedFile
foreach ($request->files as $file) {
$file = $file['file'];
break;
}
var_dump($file->guessExdtension());
}
Thanks
Try to get it from the uploaded $file->getFilename()
Then you can extract the extension using:
$fileExtension = pathinfo( $file->getFilename(), PATHINFO_EXTENSION);
In the php docs: http://php.net/manual/en/function.pathinfo.php
I've working working hard with my team to find a solution to this problem.
It seems like Symfony's library is missing a mimeType in it's core files.
You can add the mime type in:
../vendor/symfony/src/Symfony/Component/HttpFoundation/File/MineType/MimeTypeExtensionGuesser.php
In my case guessExtension() couldn't recognize .xls files.
It was missing the mime type: "application/vnd.ms-office"
So I added this line to the $defaultExtensions array in MimeTypeExtensionGuess.php :
'application/vnd.ms-office' => 'xls',
In your case it might be missing:
'application/xml' => 'xml',
Cheers! I hope this helps.
Don't edit the file directly in the vendor dir (do a pull request if need be) as when upgrading you'll lose your changes.
But use $file->getClientOriginalName()
to get the original file name that you have uploaded if $file->guessExtension()
gets you the wrong one.
I had similar problem with mp3's being recognised as mpga's