File upload with preview using JavaScript

8
Mr. Coder | 21-Oct-2024
Description

Run Code

Creating a JavaScript based file upload is simple and easy. Its code is shown in an example attached with this article. Please click on "Run Code" to see the live example.


HTML Code : 
<div class="box-file-container" align="center">
   <input multiple onchange="ShowSelectedFilesPreview(event)" type="file" id="input_file" style="display:none;" />
   <button type="button" onclick="selectFile()" >Select File</button>
   <div id="preview-container"></div>
</div>


JavaScript Code : 
 function selectFile(){
   document.getElementById("input_file").click();
}

function ShowSelectedFilesPreview(event){
   var files = event.target.files;
      for (var i = 0; i < files.length; i++) {
         document.getElementById("preview-container").innerHTML = document.getElementById("preview-container").innerHTML + '<div><img class="preview-image" alt="preview" src="'+(window.URL ? URL : webkitURL).createObjectURL(files[i])+'" /></div>';
      }
}

Above code is used to display the preview for selected file.

Comments
Load more comments.
Please Login or Sign up to comment.
logo
facebook youtube