验证base64映像laravel

hivapdat  于 2022-12-14  发布在  其他
关注(0)|答案(3)|浏览(141)

我保存一个请求到我的数据库从我的vue js通过;

public function store(Request $request)
{
  //validate
  $this->validate($request, [
     'name' => 'required',
     'description' => 'required',
     'price' => 'required'
    ]);

    //get image
    $exploded = explode(',', $request->cover_image);
    $decoded = base64_decode($exploded[1]);
    if(str_contains($exploded[0],'jpeg'))
      $extension = 'jpg';
    else
      $extension = 'png';
    $fileName = str_random().'.'.$extension;
    $path = public_path().'/cover_images/'.$fileName;
    file_put_contents($path, $decoded);

    //save
    $product = new Product;
    $product->name = $request->input('name');
    $product->description = $request->input('description');
    $product->price = $request->input('price');
    $product->cover_image = $fileName;
    if($product->save()) {
            return new ProductsResource($product);
    }
}

我如何验证base64映像?我保存来自vue js的映像的过程是正确的还是有更好的方法?请让我知道。谢谢,我只是新的laravel和vue js希望了解更多

wwtsj6pe

wwtsj6pe1#

应将此函数添加到自定义帮助器中:

if (!function_exists('validate_base64')) {

/**
 * Validate a base64 content.
 *
 * @param string $base64data
 * @param array $allowedMime example ['png', 'jpg', 'jpeg']
 * @return bool
 */
function validate_base64($base64data, array $allowedMime)
{
    // strip out data uri scheme information (see RFC 2397)
    if (strpos($base64data, ';base64') !== false) {
        list(, $base64data) = explode(';', $base64data);
        list(, $base64data) = explode(',', $base64data);
    }

    // strict mode filters for non-base64 alphabet characters
    if (base64_decode($base64data, true) === false) {
        return false;
    }

    // decoding and then reeconding should not change the data
    if (base64_encode(base64_decode($base64data)) !== $base64data) {
        return false;
    }

    $binaryData = base64_decode($base64data);

    // temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder
    $tmpFile = tempnam(sys_get_temp_dir(), 'medialibrary');
    file_put_contents($tmpFile, $binaryData);

    // guard Against Invalid MimeType
    $allowedMime = array_flatten($allowedMime);

    // no allowedMimeTypes, then any type would be ok
    if (empty($allowedMime)) {
        return true;
    }

    // Check the MimeTypes
    $validation = Illuminate\Support\Facades\Validator::make(
        ['file' => new Illuminate\Http\File($tmpFile)],
        ['file' => 'mimes:' . implode(',', $allowedMime)]
    );

        return !$validation->fails();
    }
}

然后在boot()方法中扩展AppServiceProvider中的base64_image验证:

use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        ...

        Validator::extend('base64_image', function ($attribute, $value, $parameters, $validator) {
            return validate_base64($value, ['png', 'jpg', 'jpeg', 'gif']);
        });
    }

现在,您可以在验证规则中使用它,如下所示:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'photo' => 'required|base64_image'
    ];
}
lmvvr0a8

lmvvr0a82#

有一个处理base64验证的crazybooot/base64-validation包。
有关安装说明和更多详细信息,请参阅:https://github.com/crazybooot/base64-validation

sf6xfgos

sf6xfgos3#

你可以试试这个,

Validator::extend('is_png',function($attribute, $value, $params, $validator) {
$image = base64_decode($value);
$f = finfo_open();
$result = finfo_buffer($f, $image, FILEINFO_MIME_TYPE);
return $result == 'image/png';
});

别忘了规矩:

$rules = array(
'image' => 'is_png'
);

相关问题