简体   繁体   English

Laravel - 根据请求更改文件的 MIME 类型 object

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

I'm uploading a file with dwf extension.我正在上传一个扩展名为dwf的文件。

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.然而,做$request->file('dwf_file')->extension()给我bin而不是dwf并且文件上的 mime-type 被错误地设置为application/octet-stream可能是它猜测它的原因是一个二进制文件。

Now I'm trying to change the mime-type on the fly, before validation kicks-in:现在我正在尝试在验证开始之前动态更改 mime 类型:

$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 ?那么,如何将dwf_file更改为UploadedFile的新实例? Or can I change mime-type on the exisiting UploadedFile instance?或者我可以更改现有UploadedFile实例的 mime-type 吗? I couldn't find any setMimeType method on this class.我在这个 class 上找不到任何setMimeType方法。

What are my options?我有哪些选择?

Thanks.谢谢。

You can use getClientOriginalExtension .It will return dwf extension .您可以使用getClientOriginalExtension 。它将返回dwf extension

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

And $request->file('dwf_file')->extension() will return bin .并且$request->file('dwf_file')->extension()将返回bin

You can get mimeType using您可以使用 mimeType

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

this will return "application/octet-stream"这将返回"application/octet-stream"

In form通知

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

As a side note作为旁注

getClientOriginalExtension() 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扩展无法正常用于 mimes 验证。因为 dwf 文件上传返回bin作为 mimes。所以最好创建自定义验证

  'dwf_file' => ['file','mimeTypes:application/octet-stream', function ($attribute, $value, $fail) {

            if ($value->getClientOriginalExtension() != 'dwf') {
                    $fail('The '.$attribute.' is invalid.');
                }
            }],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM