Symfony2 UploadedFile::guessExtension() for XML

2019-08-28 20:58发布

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

3条回答
Fickle 薄情
2楼-- · 2019-08-28 21:29

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.

查看更多
你好瞎i
3楼-- · 2019-08-28 21:42

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

查看更多
欢心
4楼-- · 2019-08-28 21:45

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

查看更多
登录 后发表回答