I've been researching whether JavaScript can determine if a file is a video or an image. However, most of the information I found only shows how to accept these types using the input tag.
What I really need is for JS to identify the file type and then display the file URL in either an image or video HTML tag.
Currently, when a user uploads a file, I am using the following file upload input:
<input accept="image/*,video/*" multiple="multiple" onchange='openFile(event)' style="display: none" type="file" id="selectedFile" />
Instead of having the user manually select whether it's a video or image, I want the browser to detect the file type and assign the file source to the respective element automatically.
My current code generates a data:url
for the uploaded image or video file, which is then sent through a socket to be displayed to other users on the site:
var openFile = function(file) {
var input = file.target;
var reader = new FileReader();
reader.onload = function() {
try {
var file = reader.result;
Toast.fire({
title: 'Uploading your File...',
text: " ",
didOpen: () => {
Swal.showLoading()
},
})
socket.emit('message', `
//
//
// However how can it differentiate which tag to use and use the uploaded data URL??
//
//
<video controls autoplay="1" alt="Video Uploaded" style="cursor: zoom-in; border-radius: 4px; width: 16rem" src="${file}">
<img alt="Image Uploaded" style="cursor: zoom-in; border-radius: 4px; width: 16rem" src="${file}">
`);
}
catch (err) {
}
};
reader.readAsDataURL(input.files[0]);
};
*I'm not using a blob for the file as it will not show for other users when sent through the socket. I also would rather use on file input button as I'm trying to keep things as simple for the user as possible.
TL;DR:
- User clicks a "Upload file" button
- User can upload either video or image files from the same input button
- JS create a dataURL link and finds the file format
- JS assigns which attribute tag ( or ) the file will display in
- Sends through socket for others to see
If anyone can provide assistance, it would be greatly appreciated! Thanks.