Tổng đài tư vấn: 033 688 8648
Hotline: 039 511 6390
$(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