Khi chọn ảnh để upload bởi <input type="file" />, có thể xem trước ảnh khi upload. Đoạn code này cho phép privew ảnh loại png, jpg, gif, nếu ảnh không thuộc loại này, preview sẽ hiện thị ảnh default
jQuery(document).ready(function($) {
//exec src image preview
var srcDemo = $('.img-upload > img').attr('src'); //image demo default
var allowType = ['image/jpeg','image/png','image/gif'];
var domInputFile = $("input[type=file]");
function readURL(input) {
if (input.files && input.files[0]) {
var fileUpload = input.files[0];
if($.inArray(fileUpload.type, allowType) < 0) {
$('.img-upload > img').attr('src', srcDemo); //show image default if not image type
}
else {
var reader = new FileReader();
reader.onload = function (e) {
$('.img-upload > img').attr('src', e.target.result);
}
reader.readAsDataURL(fileUpload);
}
}
}
$("input[type=file]").change(function(){
readURL(this);
});
});
Subscribe to:
Post Comments (Atom)
Anh ơi. cho hỏi nếu muốn xem trước nhiều file trước khi upload thì sao
ReplyDelete