2

I want to show the preview of selected file (video and image) before uploading them. so far i am only able to create a function to show the preview of an image like this:-

    <!-- button for selecting image/video -->
    <label for="inp-img-vid">
      <span> Photos/Videos</span>
      <input type="file" accept="image/*, video/*" name="img-vid" id="inp-img-vid">
    </label>

    <div class="display-img-vid-con">
      <!-- showing selected image here -->
      <img src="" id="preview-img">

      <!-- showing selected video here -->
      <video controls>
        <source src="" id="preview-vid">
          Your browser does not support HTML5 video.
      </video>
    </div>
    $("#inp-img-vid").change(function(){
     imgPreview(this);
    });

    function imgPreview(input){
     if(input.files && input.files[0]){
       var reader = new FileReader();
       reader.onload = function(e){
         $("#preview-img").show().attr("src", e.target.result);
       }
       reader.readAsDataURL(input.files[0]);
     }
    }

The above code shows the image inside #preview-img exactly how i want it. Now i don't know how show the video inside #preview-vid which is selected through the #inp-img-vid input tag using jquery.... any help is much appreciated.

Amit kumar
  • 137
  • 2
  • 8
  • 1
    Using the fiddle from [this answer](https://stackoverflow.com/a/32344765/2181514) with a few small changes gives [this](https://jsfiddle.net/0ya2cq61/) which seems to work fine. – freedomn-m Jan 15 '22 at 11:45
  • Does this answer your question? [change video source with file input](https://stackoverflow.com/questions/32344669/how-to-change-video-source-with-local-file-via-api-input-type-file-tag-no) – freedomn-m Jan 15 '22 at 11:46
  • @freedomn-m thanks for the reply but now i cannot select an image and preview it – Amit kumar Jan 16 '22 at 05:55
  • @freedomn-m okay this is how i am doing it now `function imgPreview(input) { var file = input.files[0]; var filetype = file['type']; var validimgtype = ["image/png", "image/jpg", "image/jpeg"]; if($.inArray(filetype, validimgtype) > 0){ alert("image"); console.log(filetype); }else{ alert("video"); console.log(filetype); } }` i am going to post an answer – Amit kumar Jan 16 '22 at 06:30
  • I just added your original reader 5 lines to the fiddle and it worked fine: https://jsfiddle.net/z3ckxjr0/ (though it did give a broken img icon, so I guess checking the type might work, but you can probably get a "bad image" event - *Edit*: [easy enough](https://jsfiddle.net/8cfbq7sv/) from [this answer](https://stackoverflow.com/questions/3019077/detecting-an-image-404-in-javascript) – freedomn-m Jan 16 '22 at 11:14

2 Answers2

3

With the help of @freedomn-m and @VC.One i came up with this answer since i know jQuery more than javascript i am going with the following code.

  $("#inp-img-vid").change(function() {
   imgPreview(this);
  });
  function imgPreview(input) {
    var file = input.files[0];
    var mixedfile = file['type'].split("/");
    var filetype = mixedfile[0]; // (image, video)
    if(filetype == "image"){
      var reader = new FileReader();
      reader.onload = function(e){
        $("#preview-img").show().attr("src", e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    }else if(filetype == "video"){
      $("#preview-vid").show().attr("src", URL.createObjectURL(input.files[0]));
      $("#videoPlayer")[0].load();
    }else{
        alert("Invalid file type");
    }
  }
Amit kumar
  • 137
  • 2
  • 8
1

In order to display any <image> and <video> from using the same <input> button then you must dynamically create such elements as needed.

This means:

  • Detect what File type the user selected.
  • Create a Path to the selected File.
  • Create the relevant Element and set Path as .src input.
  • Remove any pre-existing Element from your container (usually a <div>).
  • .append the newly created Element for display on the page.

No JQuery but this is how you can achieve with regular JavaScript code :

  • I used your Div as the container (had to add an id="display-img-vid-con" for later reference with JS).
  • Added a style="" with absolute position to control the container's X/Y coords using top and left).

( ...experiment with it)

<!DOCTYPE html>
<html>
<body>

    <!-- button for selecting image/video -->
    <label for="inp-img-vid">
      <span> Photos/Videos</span>
      <input type="file" accept="image/*, video/*" name="img-vid" id="inp-img-vid">
    </label>

    <div class="display-img-vid-con" id="img-vid-con"  style="top: 30px; left: 250px;  position: absolute; z-index: 1" >
    
      <!-- showing selected image here -->
      <!-- showing selected video here -->
    
    </div>

</body>

<script>

//$("#inp-img-vid").change( function(){ imgPreview(this); } );
document.getElementById("inp-img-vid").addEventListener("change", onFileSelected, false);

var tmpElement; //will be dynamically changed to Image or Video

var file, file_ext, file_path, file_type, file_name;


function show_Info_popUP()
{
    alert("File is selected... " + "\n name : " + file_name  + "\n type : " + file_type + "\n ext : " + file_ext );
}

function onFileSelected ( input )
{
 
    //if(input.files && input.files[0])
    if( input.target.files[0] )
    {
        file = input.target.files[0]; // FileList object
        
        file_ext; //# will extract file extension
        file_type = file.type; file_name = file.name;
        file_path = (window.URL || window.webkitURL).createObjectURL(file);
        
        //# get file extension (eg: "jpg" or "jpeg" or "webp" etc)
        file_ext = file_name.toLowerCase();
        file_ext = file_ext.substr( (file_ext.lastIndexOf(".")+1), (file_ext.length - file_ext.lastIndexOf(".")) );
        
        //# get file type (eg: "image" or "video")
        file_type = file_type.toLowerCase();
        file_type = file_type.substr( 0, file_type.indexOf("/") );
        
        let reader = new FileReader();
        reader.readAsDataURL(file);
        
        //reader.onload = function(e)
        reader.onloadend = function(evt) 
        { 
            //# POP-UP ...if you want to show (Alert box with) file details...
            show_Info_popUP();
            
            if (evt.target.readyState == FileReader.DONE) 
            {
                //# get container...
                let container = document.getElementById("img-vid-con");
                
                //# remove any already existing child element(s)
                while (container.firstChild)  
                { container.removeChild(container.firstChild); }
                
                //# if IMAGE...
                if ( file_type == "image" )
                {
                    tmpElement = document.createElement( "img");
                    tmpElement.setAttribute("id", "preview-img");
                }
                
                //# if VIDEO...
                if ( file_type == "video" )
                {
                    tmpElement = document.createElement( "video");
                    tmpElement.setAttribute("id", "preview-vid");
                    tmpElement.setAttribute("controls", "true" );
                    
                    tmpElement.addEventListener("loadeddata", () => 
                    {
                        //# what to do when some video data is loaded
                        
                        if (tmpElement.readyState >= 3) 
                        { 
                            //# what to do when video's first frame is ready
                            tmpElement.muted = true; //# if you want silent preview
                            tmpElement.play();
                        }
            
                    }); 
                }
                
                //# finalise display size
                tmpElement.width = 640; tmpElement.height = 400;
                
                tmpElement.setAttribute("src", file_path);
                container.appendChild(tmpElement);
            }
        
        }
        
    }
}
    
</script>

</html>
VC.One
  • 14,790
  • 4
  • 25
  • 57
  • thanks for this answer it is very descriptive and clearly understandable for someone like me who doesn't know much javascript. – Amit kumar Jan 17 '22 at 07:24