Search code examples
phplaravelmime-types

Laravel - change mime-type of a file on the request object


I'm uploading a file with dwf extension.

However doing $request->file('dwf_file')->extension() giving me bin instead of dwf and the mime-type on the file is wrongly set to application/octet-stream might be the reason why it is guessing it to be a binary file.

Now I'm trying to change the mime-type on the fly, before validation kicks-in:

$file = $request->file('dwf_file');

$request->merge([
    'dwf_file' =>
      new \Illuminate\Http\UploadedFile(
         $file->getPath(),
         $file->getClientOriginalName(),
         'model/vnd.dwf' // correct mime-type
     )
]);

$request->validate(...); // fails because uploaded file's extension is not dwf

It doesn't work, I think mainly because merge only deals with input source and not files.

So, How do I change the dwf_file to a new instance of UploadedFile? Or can I change mime-type on the exisiting UploadedFile instance? I couldn't find any setMimeType method on this class.

What are my options?

Thanks.


Solution

  • You can use getClientOriginalExtension.It will return dwf extension .

    $request->file('dwf_file')->getClientOriginalExtension()
    

    And $request->file('dwf_file')->extension() will return bin.

    You can get mimeType using

    $request->file('dwf_file')->getMimeType() or getClientMimeType()
    

    this will return "application/octet-stream"

    In form

    <form method="POST" enctype="multipart/form-data">
    

    As a side note

    getClientOriginalExtension()

    Returns the original file extension.It is extracted from the original file name that was uploaded.Then it should not be considered as a safe value.

    Updated

    I think dwf extension not working properly for mimes validation.Because dwf files upload return bin as mimes.So better create custom validation

      'dwf_file' => ['file','mimeTypes:application/octet-stream', function ($attribute, $value, $fail) {
    
                if ($value->getClientOriginalExtension() != 'dwf') {
                        $fail('The '.$attribute.' is invalid.');
                    }
                }],