js -显示即将上传的input 图片

点击input后有时候需要在边上显示用户刚提交的图片,通过js将临时文件输出可以显示

Posted by 昆山吴彦祖 on 2020.03.13

<input type="file"  accept="image/*"/>
<img class="img-fluid applybr" id="sample_img" src="/images/sample.jpg">
<script>
$(function () {
$('input[type=file]').change(function(){
		let reader = new FileReader();
		if ($(this).val() != '') {
			if(!(/(?:jpg|gif|png|jpeg|webp)$/i.test($(this).val()))){
				alert("只允許上傳圖片");
				return false;
			}
			reader.onload = (e) => {
			  $('#sample_img').attr('src', e.target.result);
			}
			reader.readAsDataURL(this.files[0]);
		}
	});
});
</script>