• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

167
Views
How to preview image or video when selecting a file

So I've managed the image preview where users can now select a file and preview it before uploading:

makeapost.php

   <input type="text" id="thetitle" name="title" placeholder="Title">
    <input type="text" id="imagepath" name="imagepath" hidden>
    <input type="file" name="file" onchange="readURL(this)">
    <img src="" id="img"> <br>
    <video width="320" height="240" style="display:none" controls autoplay>
    <source src="" id="forvideo">
    </video>

main.js

function readURL(input) {
  if (input.files && input.files[0]) {
    
    var reader = new FileReader();
    reader.onload = function (e) { 
      document.querySelector("#img").setAttribute("src",e.target.result);
    };

    reader.readAsDataURL(input.files[0]); 
  }
  
}

However, clearly it doesnt work with videos and I would like to know how I could preview both images and videos from one input, without having to seperate them both. Any tips? Thanks!

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use regex to detect a file type and then add extra logic for video loading.

function readURL(input) {
  //hide video frame initially
  var videoSource = document.querySelector("#forvideo");
  videoSource.parentNode.style.display = "none";
  if (input.files && input.files[0]) {

var reader = new FileReader();
reader.onload = function(e) {
  //regex to check file type
  var match = reader.result.match(/^data:([^/]+)\/([^;]+);/) || [];
  var type = match[1];

  //if file type is a video, we load video and change display style
  if (type === "video") {
    videoSource.src = URL.createObjectURL(input.files[0]);
    videoSource.parentNode.load();
    videoSource.parentNode.style.display = "block";
  }
  
  //your original logic for loading image
  if (type === "image") {
    document.querySelector("#img").setAttribute("src", e.target.result);
  }
};
reader.readAsDataURL(input.files[0]);
  }
}
   <input type="text" id="thetitle" name="title" placeholder="Title">
   <input type="text" id="imagepath" name="imagepath" hidden>
   <input type="file" name="file" onchange="readURL(this)">
   <img src="" id="img"> <br>
   <video width="320" height="240" style="display:none" controls autoplay>
     <source src="" id="forvideo">
   </video>

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error