Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel MIME issue while validating .csv file

I have read couple of post regarding the issue of checking the file extension while upload a file using laravel.

I have the same issue and didn't file the solution even if spending an hour behinding the silly thing.

this is my validation rule looks like.

public function rules()
{
    return [
       'sheet' => 'required',
       'file' => 'mimes:csv',
    ];
} 

However required is working file but on mimes.

I tried couple of other ways i founded like:

return [
    'sheet' => ['required', 'mimes:csv']
]

 

return [
    'sheet' => ['required', 'mimes:text/csv']
]

 

return [
    'sheet' => 'required|mimes:text/csv'
];

 

return [
    'sheet' => 'required|mimes:csv'
];

 

return [
    'sheet'          => 'required',
    'extension'      => 'required|in:csv'
];

Above none of line is working sometime says not valid file sometime passes through the validation.

I doubted for invalid file, then I downloaded fresh sample file from Microsoft site. That not the issue at all.

Can anyone help me?

Thanks!

like image 965
Hardik Raval Avatar asked Feb 23 '16 06:02

Hardik Raval


3 Answers

Surprised!

Its getting text/plain mime for the CSV, that was the cause of the issue.

So to fix this I just found which extension is responsible for text/plain and I found txt so i just updated my rules:

return [
    'sheet' => 'required|mimes:csv,txt'
];
like image 117
Hardik Raval Avatar answered Oct 27 '22 05:10

Hardik Raval


Here are several types I used for more complete csv validation, hope it will help future usage

        return [
            'sheet' => 'required|mimetypes:text/csv,text/plain,application/csv,text/comma-separated-values,text/anytext,application/octet-stream,application/txt'
        ];
like image 33
4givN Avatar answered Oct 27 '22 07:10

4givN


I faced the same issue, and even it is old I wish this will help the others. To fix it you must know what mime you got from your request, to find it use this line of code:

dd($request->file('document')->getMimeType(),$request->file('document')->getClientOriginalExtension() );

So in my case, the file that I uploaded is CSV but I got a txt file extension. So I solve it like the previous answers in this post by just adding txt to request validation:

return [
    'sheet' => "required|mimes:csv,txt",
];
like image 6
Ali Abbas Avatar answered Oct 27 '22 05:10

Ali Abbas