Instant Preview for Image Upload Applications JavaScript Tutorial

Published :
Author :
Adam Khoury
Learn to provide instant image previews that you can give your users in any upload applications. There may be an occasion where you want to allow the user to see or manipulate the object before it is uploaded to your server. <style> #box1{ width:500px; min-height:300px; border:1px solid #999; } #box1 > img{ width:100%; } #uploadbtn{ display:none; } </style> <script> var picobject; function chooseFile(){ if( box1.innerHTML.includes("<img src=") ){ alert("Only 1 image allowed."); return false; } file1.click(); } function instantPreview(input){ picobject = input.files[0]; var preview = document.createElement('img'); preview.src = URL.createObjectURL(picobject); box1.append(preview); uploadbtn.style.display = "inline"; } function upload(){ alert("Ajax will upload "+picobject+" now."); } </script> <div id="box1"></div> <input hidden type="file" id="file1" accept="image/*" onchange="instantPreview(this)"> <button onclick="chooseFile()">add image</button> <button id="uploadbtn" onclick="upload()">Upload</button>