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!
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>