AbirkulovSherali's avatar

Validation Blob Image

Help me, guys. I upload image in blob data to the server. And I'd like to know how to validate such data like image retrived from post-request. I've written this code, but it didn't work out for me:

$sliceContent = explode(',', $request->img['blob']);
$blobData = base64_decode($sliceContent[1]);
$imageFile = imagecreatefromstring($blobData);

 $validateImages = Validator::make(['img' => $request->img['blob']], [
            'img' => 'required|mimes:jpg,jpeg,png,bmp|max:300'
        ], [
            'img.required' => 'Картинка должна быть загружена!',
            'img.mimes' => 'Картинка должна соответствовать одному из следующих форматов: JPEG, JPG, PNG, BMP!',
            'img.max' => 'Картинка не должна превышать размер в 300кб!'
        ])->validate();
0 likes
7 replies
Cronix's avatar

Show your form and how you're uploading this file. It's hard to tell exactly what you're doing from the supplied code. AFAIK, you can't use mime types for validation unless it is an actual file uploaded, like from <input type="file">

AbirkulovSherali's avatar

Here is my form. I took only input file

<div class="form-group">
            <label for="image">Главная картинка товара:</label>
            <input type="file" class="form-control" id="image" name="image" @change="imgLoad($event.target)">
            <div class="error" v-for="error in imgOnLoadError">{{ error }}</div>
            <template v-if="form.errors.has('img')">
                <div class="error" v-for="imgError in form.errors.get('img')">
                    {{ imgError }}
                </div>
            </template>
            <div class="imgPreview" v-if="form.img !== null">
                <img :src="form.img.blob" alt="form.img.name" :title="form.img.name">
            </div>
        </div>

And method which uploads file

imgLoad(fileInput) {
                this.form.img = null;
                this.imgOnLoadError = [];

                let file = fileInput.files[0];
                let mimeType = file.type;
                let imgSize = parseInt(file.size / 1024);
                let slices = file.name.split('.');
                let extension = slices[slices.length - 1];

                let reader = new FileReader();
                reader.readAsDataURL(fileInput.files[0]);

                reader.onload = () => {
                    if(this.allowedMimeTypes.indexOf(mimeType) === -1)
                        this.imgOnLoadError.push(`Файл ${file.name} имеет недопустимый формат.`);
                    if(imgSize > 300)
                        this.imgOnLoadError.push(`Файл ${file.name} иммет размер ${imgSize} кб, что превышает допустимый размер в 300кб.`);
                    if(this.allowedExtensions.indexOf(extension) === -1)
                        this.imgOnLoadError.push(`Файл ${file.name} имеет недопустимое расширение.`)

                    if(this.imgOnLoadError.length)
                        return false;

                    this.form.img = {name: file.name, blob: reader.result}
                }
            },
Cronix's avatar

Ok. I don't know how you can validate that with the built in validation rules since it's not an actual file being uploaded.

If it was just

<input type="file" class="form-control" id="image" name="image">

and not doing something like reader.readAsDataURL(fileInput.files[0]);, then what you have would work since it's a real file being uploaded. You're basically sending a string, which wouldn't have a mime type to check against.

Is there a reason why you need to send it the way you are and not just upload a regular file?

AbirkulovSherali's avatar

Cronix, I'm just intersting. I know there is FormData Api. But I'd like to know about uploading blob data and how to validate it. But thank you anyway )

Cronix's avatar
Cronix
Best Answer
Level 67

See if this helps: https://medium.com/@jagadeshanh/image-upload-and-validation-using-laravel-and-vuejs-e71e0f094fbb

They had to make their own custom validation rule, but it shows how. Seems like a lot of extra work when you can just upload a regular file.

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

Please or to participate in this conversation.