Replacement for File::mime() in Laravel 4 (to get mime type from file extension)

后端 未结 5 1002
名媛妹妹
名媛妹妹 2020-12-06 17:20

Laravel 3 had a File::mime() method which made it easy to get a file\'s mime type from its extension:

$extension = File::extension($path);
$         


        
5条回答
  •  Happy的楠姐
    2020-12-06 18:23

    It turned out that Symfony ExtensionGuesser and MimeTypeGuesser use unreliable FileInfo class. For that reason validation of mimes return unpredictable results and can not be used with files uploads in a proper way (it returns text/plain mime for js, xls, po etc.).

    I've found very simple solution for this problem.

    Instead of

    'attachment' => 'required|mimes:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt|max:10000',
    

    I split that into two different parts and now my validation looks like this:

    private function createFileAttachmentValidator($file)
    {
        return Validator::make(
            [
                'attachment' => $file,
                'extension'  => \Str::lower($file->getClientOriginalExtension()),
            ],
            [
                'attachment' => 'required|max:10000',
                'extension'  => 'required|in:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt',
            ],
            $this->validationMessages()
        );          
    }   
    

    I simply try to verify that extension of the file is present and that it is listed in my in rule. That works, however, solution is not perfect.

提交回复
热议问题