验证base64图像laravel

时间:2018-07-19 09:41:54

标签: php laravel laravel-5

我通过以下方式将请求从我的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的新手,希望了解更多信息

2 个答案:

答案 0 :(得分:0)

您可以尝试一下,

"right"

别忘了规则:

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';
});

答案 1 :(得分:0)

您应该将此功能添加到自定义帮助程序中:

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();
    }
}

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

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'
    ];
}