VANHIEP.NET - Làm web giá rẻ - Thiết Kế Website - Thiết Kế Ứng Dụng Mobile
Cách render hình ảnh khi chọn thẻ input thay đổi

Cách render hình ảnh khi chọn thẻ input thay đổi


$(function()
{
    $('#img').on('change',function ()
    {
        var filePath = $(this).val();
        // $("#img_display").attr("src", filePath)
        console.log('filePath', filePath);

        const preview = document.querySelector('#img_display');
        const file = document.querySelector('#img').files[0];
        const reader = new FileReader();

        reader.addEventListener("load", function () {
            // convert image file to base64 string
            preview.src = reader.result;
        }, false);

        if (file) {
            reader.readAsDataURL(file);
        }
    });
});

Ta sẽ bắt sự kiện thay đổi hình ảnh do người dùng chọn file mới

Khai báo biến preview là thẻ img hiển thị ảnh sau khi render

Khai báo biến file là thẻ input chọn file

Sử dụng hàm render của javacript khai báo như trên. Thế là ok