Javascript & jQuery

Image preview

22.07.2021 2 dəq oxuma Yeniləndi: 29.07.2021

 1.in html file

<div class="form-group mb-5">
    <div class="form-group">
        <label for="photo" class="form-label">Photo</label>
        <div class="col-sm-10">
            <div class="dropzone">
                <img id="preview" src="{{ asset('assets/images/Add-photo-icon.png') }}" alt="Add photo icon"/>
                <input type="file" name="photo" class="upload-input" id="photo" value="{{ old('photo') }}" aria-describedby="photoHelp"/>
            </div>
        </div>
        @error('photo')
        <small id="photoHelp" class="form-text text-danger">{{ $message }}</small>@enderror
    </div>
</div>

2.in css file

#preview{
    height: 78px;
    width:78%;
}
.dropzone {
    width: 100px;
    height: 80px;
    border-radius: 3px;
    text-align: center;
}

.upload-input {
    position: relative;
    top: -78px;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

3.in js file

$( document ).ready( function () {
    $( 'input[type=file]' ).change( function ( event ) {
        let val = $( this ).val().toLowerCase(),
            regex = new RegExp( '(.*?)\.(png|jpeg|jpg)$' );

        if ( $( this )[ 0 ].files.length !== 1 )
        {
            $( this ).val( '' );
            toastr.error( 'You can only upload one image', 'Attention' );
            $( '#preview' ).attr( 'src', '/assets/images/Add-photo-icon.png' );
        }
        else if ( ! ( regex.test( val ) ) )
        {
            $( this ).val( '' );
            toastr.error( 'Please only add images in png, jpeg, jpg format', 'Attention' );
            $( '#preview' ).attr( 'src', '/assets/images/Add-photo-icon.png' );
        }
        else
        {
            $( '#preview' ).attr( 'src' );
            let reader = new FileReader();
            reader.onload = function () {
                let preview = document.getElementById( 'preview' );
                preview.src = reader.result;
            };
            
            let img = new Image()
            img.src = window.URL.createObjectURL(event.target.files[0])
            img.onload = () => {
                if (img.width === 1920 && img.height === 685)
                {
                    reader.readAsDataURL( event.target.files[ 0 ] );
                }
                else
                {
                    $( this ).val( '' );
                    toastr.error( 'Please only add images 1920x685', 'Attention' );
                }
            }

        }
    } );
} );

 

Digər dildə: EN