I am trying to upload a CSV file and I want to validate it before doing anything else. So I use the following code in my FormRequest:
public function rules()
{
return [
'csvFile' => 'required|file|mimes:csv'
];
}
The form i use for uploading the file is:
<form action="{{ route('uploadFile') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="fileToUpload">CSV File to upload</label>
<input name="csvFile" type="file" class="form-control" id="fileToUpload" placeholder="Select file">
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
The problem is that it does not work. Trying to check the mime type of my test.csv file using getMimeType() I get:
"text/plain"
but if I use getClientMimeType() I get:
"text/csv"
From what I read is that:
The client mime type (getClientMimeType()) is extracted from the request from which the file was uploaded, so it should not be considered as a safe value.
For a trusted mime type, use getMimeType() instead (which guesses the mime type based on the file content).
Obviously, I should use getMimeType(), but it will not work (at least most of the times).
I tried to imitate this by doing:
end(explode('.', $file->getClientOriginalName()));
This will return 'csv' as a result, but it feels like a hack! Also, it can be fooled easily.
Is there a way to safely know if a file is of type .csv?
Thanks!
you can use required|mimes:csv,txt
for validation csv file.
As CSV is basically a text-file, so its mime-type is checked against the file extension. Does your file have a .csv extension?
If you want to allow .txt extension as well, change your validation rule to this:
return [ 'csv_import' => 'required|mimes:csv,txt' ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With