File API
by Евгений
HTML
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/5.3.3/css/foundation.min.css">
<div class="container">
<div class="row">
<!-- the photo demo-->
<div class="large-12 columns">
<h1>Load A Photo</h1>
<input type="file" id="the-photo-file-field">
<div id="preview">
<!--image will be inserted here-->
</div>
<div id="data" class="large-8 columns">
<h2 id="name"></h2>
<p id="size"></p>
<p id="type"></p>
</div>
</div>
<!-- the video demo-->
<div class="large-12 columns">
<h1>Load An mp4 file</h1>
<input type="file" id="the-video-file-field">
<div id="data-vid" class="large-8 columns">
<!--video will be inserted here.-->
</div>
<h2 id="name-vid"></h2>
<p id="size-vid"></p>
<p id="type-vid"></p>
</div>
</div>
</div>
<!--
notes
html5 video
https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats
-->
JavaScript
//check if browser supports file api and filereader features
if (window.File && window.FileReader && window.FileList && window.Blob) {
//this is not completely neccesary, just a nice function I found to make the file size format friendlier
//http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable
function humanFileSize(bytes, si) {
var thresh = si ? 1000 : 1024;
if (bytes < thresh) return bytes + ' B';
var units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while (bytes >= thresh);
return bytes.toFixed(1) + ' ' + units[u];
}
//this function is called when the input loads a video
function renderVideo(file) {
var reader = new FileReader();
reader.onload = function(event) {
the_url = event.target.result
//of course using a template library like handlebars.js is a better solution than just inserting a string
$('#data-vid').html("<video width='400' controls><source id='vid-source' src='" + the_url + "' type='video/mp4'></video>")
$('#name-vid').html(file.name)
$('#size-vid').html(humanFileSize(file.size, "MB"))
$('#type-vid').html(file.type)
}
//when the file is read it triggers the onload event above.
reader.readAsDataURL(file);
}
$("#the-video-file-field").change(function() {
console.log("video file has been chosen")
//grab the first image in the fileList
//in this example we are only loading one file.
console.log(this.files[0].size)
renderVideo(this.files[0])
});
} else {
alert('The File APIs are not fully supported in this browser.');
}