Site icon Régis Enguehard

Prévisualiser l’image après l’avoir sélectionner via un input de type file

La partie javascript

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
    $(document).ready(function (e) {
        $('input[type="file"]').on('change', (e) => {
            console.log('change file');
            let that = e.currentTarget
            if (that.files && that.files[0]) {
                $(that).next('.custom-file-label').html(that.files[0].name)
                let reader = new FileReader()
                reader.onload = (e) => {
                    $('#preview').attr('src', e.target.result)
                }
                reader.readAsDataURL(that.files[0])
            }
        })
    });
</script>

Le marquage HTML (avec les classes Bootstrap 4)

<div class="custom-file">
    <input accept="image/png, image/jpeg" type="file" name="avatar" id="avatar" class="custom-file-input" value="">
    <label for="avatar" class="custom-file-label">Avatar</label>
    <img id="preview" class="w-50 img-fluid">
</div>
https://blog.enguehard.info/wp-content/uploads/2020/02/previsualiser-image-input-file.mp4
Quitter la version mobile