Skip to content

Instantly share code, notes, and snippets.

@vihoangson
Last active December 25, 2019 01:45
Show Gist options
  • Save vihoangson/8f6c3e92516072cc83426c4298794344 to your computer and use it in GitHub Desktop.
Save vihoangson/8f6c3e92516072cc83426c4298794344 to your computer and use it in GitHub Desktop.
// Vào một ngày đẹp trời tôi có nhã hứng muốn chọn file và hiện thị preview lên giao diện ngay lập tức. Sau đây là code thực hiện.
<img>
<input type="file">
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script>
$("input[type=file]").on('change', function () {
var preview = document.querySelector('img'); // Image reference
var file = document.querySelector('input[type=file]').files[0]; // File refrence
var reader = new FileReader(); // Creating reader instance from FileReader() API
reader.addEventListener("load", function () { // Setting up base64 URL on image
preview.src = reader.result;
}, false);
reader.readAsDataURL(file);
})
</script>
@vihoangson
Copy link
Author

previewByFileReader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment