'Laravel validator and excel files error
I have an input field who allaow peoples to upload files. I want that they can upload, word files like doc, and files like csv,xlsx.
When i try with a .doc no problem at all but when i try with an excel files, the validator fail and say that not the good extension.
Here you can see my code, the two lines of comments was an other solution i have try , and it don't work too :(.
Any help is welcome.
public function postFile(Request $request)
{ //Règle de validation avec les type de fichiers acceptés
if(isset($request->file)){
//dd($request);
$validator=Validator::make($request->all(),[
'file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp,application/csv,application/excel,
application/vnd.ms-excel, application/vnd.msexcel,
text/csv, text/anytext, text/plain, text/x-c,
text/comma-separated-values,
inode/x-empty,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
/* 'extension' => strtolower($request->file->getClientOriginalExtension()),
'extension'=>'required|in:doc,csv,xlsx,xls,docx,ppt,odt,ods,odp'*/
]);
if ($validator->fails()) {
return back()
->withErrors($validator);
}
Solution 1:[1]
Use "mimes" when you want to write an extentions (xlsx,doc,docx). In case when use mime-type like application/vnd.ms-excel you must use validation rule mimetype
More mime types: more mime-types
$validator=Validator::make($request->all(),[
//use this
'file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp'
//or this
'file'=>'required|max:50000|mimetypes:application/csv,application/excel,
application/vnd.ms-excel, application/vnd.msexcel,
text/csv, text/anytext, text/plain, text/x-c,
text/comma-separated-values,
inode/x-empty,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
]);
Solution 2:[2]
Here's how I did it in Laravel 6 by checking the file extension.
Create a new validation rule:
php artisan make:rule ExcelRule
Here is the ExcelRule, which checks the file extension:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\UploadedFile;
class ExcelRule implements Rule
{
private $file;
public function __construct(UploadedFile $file)
{
$this->file = $file;
}
public function passes($attribute, $value)
{
$extension = strtolower($this->file->getClientOriginalExtension());
return in_array($extension, ['csv', 'xls', 'xlsx']);
}
public function message()
{
return 'The excel file must be a file of type: csv, xls, xlsx.';
}
}
As you can see, I'm checking for csv, xls, or xlsx here. You can add any additional extensions you desire.
Using it in a controller:
public function uploadExcelFile(Request $request)
{
$request->validate([
'excel_file' => ['required', new ExcelRule($request->file('excel_file'))],
]);
$model->update([
'excel_file' => $request->file('excel_file')->store('excel_files'),
]);
return redirect()->route('my_route_name')->with('Excel file uploaded!');
}
Solution 3:[3]
First tell that this is not the proper solution. But you can try this.
I've searched also for that and having so much trouble validating excel file and their mimes type is not working for that unfortunately.
if($request->hasFile('file'))
{
$extension = File::extension($request->file->getClientOriginalName());
if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {
//'Your file is a valid xls or csv file'
}else {
//'File is a '.$extension.' file.!! Please upload a valid xls/csv file..!!');
}
}
in namspace include must use File;
You can validate any file by this way, Thanks.
Solution 4:[4]
In Laravel you can use validate the file upload with extension using After Hooks. Read more from here!
$validator->after(function ($validator) use ($request){
if($this->checkExcelFile($request->file('file')->getClientOriginalExtension()) == false) {
//return validator with error by file input name
$validator->errors()->add('file', 'The file must be a file of type: csv, xlsx, xls');
}
});
function checkExcelFile($file_ext){
$valid=array(
'csv','xls','xlsx' // add your extensions here.
);
return in_array($file_ext,$valid) ? true : false;
}
Solution 5:[5]
I tried validators provided by laravel but all doesnt seems to work.. That gave me an idea to try to validate using normal php and it works like a cham
$extensions = array("xls","xlsx","xlm","xla","xlc","xlt","xlw");
$result = array($request->file('import_file')->getClientOriginalExtension());
if(in_array($result[0],$extensions)){
// Do something when Succeeded
}else{
// Do something when it fails
}
Solution 6:[6]
That is it! I tried it myself and if you only test for mimes:csv it will fail when the filename has an space.
What I did to pass validation was to use required|mimes:csv,txt.
But as you already suggested you would need to do some manual validation.
Front-end validation is a good thing regarding the user experience, but you can never trust solely in a validation that ran in a machine different than your server. If you are going to do any javascript validation, always validate it again in the server.
In your case, as it is an exception regarding an unusual filename, not an wrong format, I would relax the mime-type validation using mimes:csv,txt and then use a package to parse the CSV file, generally this packages raises an exception when the format is not valid.
Two great packages for dealing with CSV are:
[ https://github.com/Maatwebsite/Laravel-Excel ] [ http://csv.thephpleague.com/ ] Hope it helps.
[ https://laracasts.com/discuss/channels/general-discussion/csv-file-upload-request-validation ]
Solution 7:[7]
Simple solution is using mime
$request->validate([
'file'=> 'required|mimes:xlsx, csv, xls'
]);
Solution 8:[8]
This:
'file' => 'required|mimes:xlsx, xls',
may not work because you forgot to put this:
enctype="multipart/form-data"
in your html form tag!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
