我想通过输入按钮获取视频的宽度和高度。但是我的代码不起作用。我得到了文件,但是我想从文件变量中获得信息。
fileButton.addEventListener('change', function(e) {
//Get file
var file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(){
var height =reader.naturalHeight;
var width =reader.naturalWidth;
}
});
答案 0 :(得分:2)
使用FileReader将其从二进制转换为base64,然后再转换回二进制是浪费资源和内存的,请改用URL.createObjectURL。而且您不必将视频附加到DOM
fileButton.addEventListener('change', evt => {
const file = fileButton.files[0]
const url = URL.createObjectURL(file)
const video = document.createElement('video')
video.onloadedmetadata = evt => {
// Revoke when you don't need the url any more to release any reference
URL.revokeObjectURL(url)
console.log(video.videoWidth, video.videoHeight)
}
video.src = url
video.load() // fetches metadata
})
<html>
<input type="file" id="fileButton">
答案 1 :(得分:-1)
尝试一下:
<html>
<input type="file" id="load-file">
<button type="button" id="done-button">Check</button>
<script src="https://cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
<script>
(function ($) {
$('#done-button').on('click', function () {
var file = $('#load-file')[0].files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
var dataUrl = reader.result;
var videoId = "videoMain";
var $videoEl = $(`<video id="${videoId}" style="display: none"></video>`);
$("body").append($videoEl);
$videoEl.attr('src', dataUrl);
var videoTagRef = $videoEl[0];
videoTagRef.addEventListener('loadedmetadata', function (e) {
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
})(jQuery);
</script>
</html>