我有一个基于Web的用户界面,便于将文件拖放到容器DIV中。如果删除的文件是图像,我使用以下代码:
let droppedFile = evt.dataTransfer.files[0];
let img = new Image();
let reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
let fileDetails = {};
let n = droppedFile.name.indexOf('.');
fileDetails.name = droppedFile.name.substring(0, n != -1 ? n : droppedFile.name.length);
fileDetails.extension = droppedFile.name.substring(n != -1 ? n+1 : '');
fileDetails.fileType = droppedFile.type;
fileDetails.width = img.naturalWidth;
fileDetails.height = img.naturalHeight;
// display fileDetails in another DIV...
}
reader.readAsDataURL(droppedFile);
我需要能够对视频文件(例如MP4)做同样的事情。但是,我没有看到任何Video
元素,类似于Image元素/构造函数。如何实例化视频元素,以便获取通用属性以及视频特定属性?
答案 0 :(得分:1)
您不需要使用FileReader。使用以下代码:
const video = document.createElement('video')
video.addEventListener('loadedmetadata', event => {
console.log(video.videoWidth, video.videoHeight)
})
video.src = URL.createObjectURL(droppedFile)
完整代码:
const dropzone = document.getElementById('dropzone')
dropzone.addEventListener('dragover', event => event.preventDefault())
dropzone.addEventListener('drop', event => {
event.preventDefault()
const droppedFile = event.dataTransfer.files[0]
const video = document.createElement('video')
video.addEventListener('loadedmetadata', event => {
console.log(video.videoWidth, video.videoHeight)
})
video.src = URL.createObjectURL(droppedFile)
})
*, ::before, ::after {
box-sizing: border-box;
}
#dropzone {
width: 600px;
height: 300px;
border: 2px dashed blue;
border-radius: 3px;
background-color: white;
color: gray;
font-family: sans-serif;
font-size: 22px;
display: flex;
justify-content: center;
align-items: center;
transition: 400ms;
}
#dropzone:hover {
cursor: pointer;
}
<div id="dropzone">drop files here</div>
答案 1 :(得分:1)
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = (e) => {
var videoElement = document.createElement('video');
videoElement.src = e.target.result;
var timer = setInterval(() => {
if (videoElement.readyState === 4) {
if(videoElement.duration) {
console.log(file)//the file object
console.log(videoElement.duration) //video duration
}
clearInterval(timer);
}
}, 500)
}
reader.readAsDataURL(file);