M
M
Maxim Volkov2021-07-22 13:26:36
Laravel
Maxim Volkov, 2021-07-22 13:26:36

How to validate when uploading files with different extensions: pdf, doc, docx, jpg, jpeg, png, ppt, txt, tif, xls, xlsx?

I ask for advice!

The goods provide for downloading documentation in files with various extensions: pdf, doc, docx, jpg, jpeg, png, ptt, txt, tif, xls, xlsx .

Problem with file validation on upload.

Validation rule: 'file'=> 'mimes:jpg,gif' – not suitable for the specified extension types.

Validation by mimetypes also fails. For example, the validation rule with valid file types is specified in the controller:

$messages = [
            'file' => 'Файл документа должен иметь расширение: pdf,doc,docx,jpg,jpeg,png,ppt,txt,tif,xls,xlsx',
            'file.size' => 'Размер документа не должен превышать 10 мб.'
        ];
        $this->validate($request, [
            'file' => 'mimetypes:application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/jpeg,image/png,application/vnd.ms-powerpoint,text/plain,image/tiff,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet|nullable',
            'file.size' => '10248|nullable'
        ],$messages);

Does not work, all files are loaded: video - *.mp4, audio - *.mp3, *.psd - which are not in the mimetypes list.

Advise how to validate when uploading files with the specified extensions. I would be grateful for any information on how to solve the problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2021-07-22
@voland700

'file' => 'mimetypes:application/pdf
replace with
'file' => 'mimes:application/pdf
or check yourself, which is more flexible

<?php
$file = request()->file('file');
$ext = $file->getClientOriginalExtension();
$ext = strtolower($ext);
if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
  return response()->json([
   'errors' => [
     'file' => 'INVALID_EXTENSION',
    ]
   ], 400);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question