簡體   English   中英

通過 inertiajs form.post 上傳的圖片在 Laravel 8 中未通過 mime 圖片驗證

[英]Image uploaded through inertiajs form.post fails mime image validation in Laravel 8

Laravel 版本:8.82.0

我正在通過使用form.post方法發出發布請求來使用 inertiajs 上傳圖像。 在 controller 中收到圖像數據,如下圖所示:

在此處輸入圖像描述

我的簡化版 controller:

public function store(){
    
    Request()->validate([
        'thumbnail' => 'required|mimes:png,jpeg,jpg|max:2048'

        // Also tried, still fails.
        // 'thumbnail' => 'required|image|mimes:png,jpeg,jpg|max:2048'

    ]);
    
    return Redirect::route('showcases.index');

}

到達后 header 內容類型為application/json ,我嘗試將其更改為multipart/form-data但無濟於事,圖像驗證仍然失敗。

我得到的錯誤是: The thumbnail must be a file of type: png, jpeg, jpg

您正在嘗試驗證 base64 字符串而不是文件。 在字符串格式 laravel 中,驗證無法驗證 MIME 類型。 所以你可以嘗試擴展驗證規則並嘗試更好的方法。 AppServiceProvider內部放置自定義驗證(還有許多其他更簡潔的方法)

public function boot()
{
    Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
        $type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
        if (in_array($type, $parameters)) {
            return true;
        }
        return false;
    });

    Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
        return str_replace(':values',join(",",$parameters),$message);
    });
}

現在你可以這樣做:

'thumbnail' => 'required|image64:jpeg,jpg,png'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM