Fermer

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>

2 réponses à “Prévisualiser l’image après l’avoir sélectionner via un input de type file

  1. Hello, hope you’re doing great, I really liked the code and it helped so much but I have a little problem, is that I can’t adjust the seize of the image that I’m uploading, can you help me and tell me how to get a solution for this problem? thank you so much and have a great day !

Laisser une réponse à OBEID Fouad Annuler la réponse

Votre adresse email ne sera pas publiée. Les champs obligatoires sont indiqués par *