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

0

157
Views
Cómo obtener una vista previa de la imagen o el video al seleccionar un archivo

Así que administré la vista previa de la imagen donde los usuarios ahora pueden seleccionar un archivo y obtener una vista previa antes de cargarlo:

hacerpost.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>

principal.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]); } }

Sin embargo, claramente no funciona con videos y me gustaría saber cómo puedo obtener una vista previa de imágenes y videos desde una sola entrada, sin tener que separarlos. ¿Algun consejo? ¡Gracias!

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

0

Puede usar expresiones regulares para detectar un tipo de archivo y luego agregar lógica adicional para la carga de video.

 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