How do I upload video to server after previewed using phonegap - javascript

Pls I urge for assistance on how to upload video captured with phonegap android app. I could upload captured video, but I want the user of the app to watch the captured video before uploading it. That is where I'm having problem.
The code I am using is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css" />
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script src="js/modernizr-latest.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#takeVideo").addEventListener("touchend", function() {
alert("Take video");
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1, duration: 10});
}, false);
}
function captureError(e) {
console.log("capture error: "+JSON.stringify(e));
}
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
}
function uploadFile(s) {
// Get URI of picture to upload
var img = document.getElementById('videoArea');
var mediaFile = img;
alert(mediaFile);
if (!mediaFile || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
var ft = new FileTransfer(),
path = mediaFile.substr(mediaFile.lastIndexOf('/')+1),
name = mediaFile.name;
var options = new FileUploadOptions();
options.mimeType = "document";
options.fileName = name;
options.chunkedMode = true;
options.params = params;
ft.upload(path,
"http://www.example.com/folder/upload.php",
function(result) {
alert('Upload success: ' + result.responseCode);
alert(result.bytesSent + ' bytes sent');
},
function(error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
}
</script>
</head>
<body>
<button id="takeVideo">Take Video</button><br>
<b>Status:</b> <span id="camera_status"></span><br>
<div id="videoArea"></div>
<button type="submit" onclick="uploadFile();">Submit</button>
</body>
</html>
Pls I count on your assistance to solve this challenge. I do not know how to reference "video" tagname nor extract image path from the videoArea id of the div.

Related

how to define a var from json to js?

I'm a newbie in javascript and need your help.
I don't know what to do and how to do to make this working:
I have the following js and html code:
var slides = '';
var slideImg = slider.images;
var i;
for (var i=0; i<slider.images.length; i++) {
slides += '<div id="slide'+i+'" class="slideEl" ><img src="'+slider.images[i].src+'"><div class="container-images">'+slider.images[i].CTA.text+'</div></div>';
}
document.getElementById('slides').innerHTML = slides;
document.getElementById('slides').style.width = window.innerWidth * (slideImg.length) + 'px';
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
document.getElementById('slides').style.left = 0;
var indexSlide = 0;
function moveSlide(params) {
var slideWidth = document.getElementsByClassName('slideEl')[0].offsetWidth;
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
var element = document.getElementById('slides');
var rect = element.getBoundingClientRect();
var newPos = rect.left;
if(params == 'right' && indexSlide < slideImg.length -1){
newPos -= slideWidth;
indexSlide++;
} else if (params == 'left' && indexSlide > 0) {
newPos += slideWidth;
indexSlide--;
}
document.getElementById('slides').style.transitionDuration = slider.images[indexSlide].speed + 's';
document.getElementById('slides').style.left = newPos + 'px';
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS exercise</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="media/favicon-32x32.png" />
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<div id="slider">
<div id="slides" class="slides"></div>
<div class="container-slider">
<span id="arrowLeft" class="arrow" onclick="moveSlide('left')">〈</span>
<span id="arrowRight" class="arrow" onclick="moveSlide('right')">〉</span>
</div>
</div>
<footer>Copyright © 2019</footer>
<script language="javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/data.json"></script>
</body>
</html>
and besides that, I have another file called data.json:
[{
"autoplay" : "yes",
"transition" : "slide",
"images" :[
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://www.test.com",
"position" : "bottom-right"
}
}
]
}]
How can I get the slider var from json to javascript just to defined the length of the whole slider?
EDIT(from answer):
#Mrunmay Deswandikar, I've added this piece of code at the start of my script.js file:
var xhttp = new xmlhttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "http://wip.2mo.ro/sandra/js-slider/js/data.json", true);
xhttp.send();
var slides = '';
var slideImg = slider.images;
.....
I got this error: Uncaught ReferenceError: xmlhttpRequest is not defined
at script.js:1
(anonymous) # script.js:1
What am I missing?
Many thanks,
Sandra
Script tags are not meant to be used to load json data. Use fetch instead.
fetch('js/data.json')
.then(res=>res.json())
.then(data=>{
const slider = data.shift();
/** rest of your code here */
})
.catch(err=>{
console.log(err.message);
});
Fetch by default uses promises, but if you prefer to use it with async/await (syntaxical sugar for Promises).
async function loadData(){
const res = await fetch('/js/data.json');
const data = await res.json();
const slider = data.shift();
/** rest of code here */
}
loadData().catch(err=>console.log(err);
To get the data from json, use Ajax request to load JSON file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "data.json", true);
xhttp.send();
This will get all the data of data.json file, into variable data.
If your data.json file is located at the same directory, else you can use releative path, but best way will be use server path, like,
xhttp.open("GET","https://yourwebsite/DIRECTORY/data.json",true);

Trying loading external plugin on click doesn't work

What I want to achieve is that, when I click on a button, an overlay div containing the Dropzone.js form is created and displayed.
Here's the "normal" script I used before, and everything works fine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
</head>
<body>
<h1>Upload your files</h1>
<form action="uploads" method="post" enctype="multipart/form-data" class="dropzone" id="my-dropzone">
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: 1, // MB
maxFiles: 1,
acceptedFiles: ".jpg",
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
};
</script>
</body>
</html>
Here's the script that doesn't work:
$(document).ready(function () {
/**
* Promises to load the Dropzone.js files on CDNs
*/
function myAsyncFunction(type, url) {
return new Promise(function (resolve, reject) {
if (type === "js") {
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
} else if (type === "css") {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
}
})
}
/**
* Overlay div
*/
var uploadDiv = function (__callback) {
var div = document.createElement('div');
div.setAttribute('id', 'dropzone-container');
document.body.appendChild(div);
var h1 = document.createElement('h1');
h1.textContent = "Upload file";
div.appendChild(h1);
var form = document.createElement('form');
form.setAttribute('action', 'uploads');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('class', 'dropzone');
form.setAttribute('id', 'my-dropzone');
div.appendChild(form);
__callback();
};
/**
* Does the job and call the Dropzone object
*/
var upload = function () {
// Get data-options
var options = JSON.parse(this.dataset.options);
// Create HTML
uploadDiv(function () {
myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
.then(
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
.then(
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: options.maxFilesize, // MB
maxFiles: options.maxFiles,
acceptedFiles: options.acceptedFiles,
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
}
)
)
});
}
/**
* Attach EventListener.
* #type {HTMLCollectionOf<Element>}
*/
var btnUpload = document.getElementsByClassName('mb-upload');
for (var i=0; i<btnUpload.length; i++) {
btnUpload[i].addEventListener("click", upload);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">
</body>
</html>
As you can see, the div is created and the Dropzone.js files are loaded, but the Dropzone form doesn't work as in the previous snippet.
Where am I wrong?
You had a syntax error,
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js').then(()=>{
//resolve function
})
$(document).ready(function () {
/**
* Promises to load the Dropzone.js files on CDNs
*/
function myAsyncFunction(type, url) {
return new Promise(function (resolve, reject) {
if (type === "js") {
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
} else if (type === "css") {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
}
})
}
/**
* Overlay div
*/
var uploadDiv = function (__callback) {
var div = document.createElement('div');
div.setAttribute('id', 'dropzone-container');
document.body.appendChild(div);
var h1 = document.createElement('h1');
h1.textContent = "Upload file";
div.appendChild(h1);
var form = document.createElement('form');
form.setAttribute('action', 'uploads');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('class', 'dropzone');
form.setAttribute('id', 'my-dropzone');
div.appendChild(form);
__callback();
};
/**
* Does the job and call the Dropzone object
*/
var upload = function () {
// Get data-options
var options = JSON.parse(this.dataset.options);
// Create HTML
uploadDiv(function () {
myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
.then(
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
.then(()=>{
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: options.maxFilesize, // MB
maxFiles: options.maxFiles,
acceptedFiles: options.acceptedFiles,
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
}
})
)
});
}
/**
* Attach EventListener.
* #type {HTMLCollectionOf<Element>}
*/
var btnUpload = document.getElementsByClassName('mb-upload');
for (var i=0; i<btnUpload.length; i++) {
btnUpload[i].addEventListener("click", upload);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">
</body>
</html>

Uploading video from phonegap to php

I am using this phonegap(js) code to upload a recorded video to php server.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<title>Mobile_Insurance</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="visit"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureVideo() {
// Launch device video recording application,
// allowing user to capture up to 2 video clips
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
var options = new FileUploadOptions();
options.chunkedMode = true;
options.fileKey = "file";
options.fileName = name;
options.mimeType = "video/mp4";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
ft.upload(path, "http://192.168.0.46/upload/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
console.log("Response = " + r.response);
alert("Response = " + r.response);
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
alert(mediaFile.fullPath);
}
</script>
<script type="text/javascript" src="cordova.js"></script>
<div data-role="page">
<div data-role="header">
<h3>Welcome </h3>
</div>
<div data-role="main" class="ui-content">
<h3 style="text-align: center;">Input Your IMEI:</h3>
<input type="number"/>
<h3 style="text-align: center;"> yes?</h3>
<input type="radio" name="visit" value="YES" id="Video"> YES
<input type="radio" name="visit" value="NO" id="self"> NO
<br>
<h3 style="text-align: center;"> damage.</h3>
<input type="radio" name="damage" value="Physical"> Physical
<input type="radio" name="damage" value="Water"> Water <br><br>
<h3 style="text-align: center;">Please give a breig description about the damage</h3><br>
<textarea rows="5" cols="10" style="resize:none"></textarea>
<div class="YES box"><input type="button" value="self analysis" hidden="true"></div>
<div class="NO box"> <button onclick="captureVideo();">Capture Video</button></div>
</div>
</div>
</body>
</html>
This is my php code..
<?php
print_r($_FILES);
$new_image_name = "r.mp4";
move_uploaded_file($_FILES["file"]["tmp_name"], $new_image_name);
?>
The uploadFile function is supposed to upload the file to the specified php file. but in my case the phonegap filetransfer is giving error code 1 which is file not found. I have alert the file path after capture which is same file to be uploaded. How is it throwing error code 1?
Try this, you might be able to use this
http://findnerd.com/list/view/Capturing-and-Uploading-Video-to-PHP-Server-in-Cordova/9398/
From the site:
If you want to send image as base64 string you can change destination
type to Camera.DestinationType.DATA_URL and you can send imageData to
server via ajax call. or, if you want to send as file array then keep
the same destination type to camera.DestinationType.FILE_URI and use
cordova file plugin to send file data in server:
var options = new FileUploadOptions();
options.fileKey="tickitFile";
options.fileName=imageData.substr(imageData.lastIndexOf('/')+1);
options.contentType = "multipart/form-data";
options.chunkedMode = false;
options.mimeType="image/jpeg";
options.httpMethod="POST";
options.headers = {
Connection: "close"
};
var ft = new FileTransfer();
ft.upload(imageData, PHP_URL, win, fail, options);
function win(r) {
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log(JSON.stringify(error));
}
you can try this below :
function upload(file){
var fd = new FormData();
fd.append("dir", dir);
fd.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.send(fd);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
//alert(xhr.responseText);
var message = xhr.responseText;
message=message.trim();
if ( message != 0)
{
//alert(message);
}
}
};
}
and the php file :
<?php
if (isset($_FILES["file"]["name"])) {
$destination = $_POST["dir"];
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
//echo $name;
//echo $tmp_name;
//echo $error;
move_uploaded_file($_FILES['file']['tmp_name'], $destination.$name);
}
echo "File transfer completed";
?>
XHR POST has no size limit, but you're sending data to PHP which has a size limit ;) Create the following php-file and open it in a browser:
Now search for the variable "post_max_size", this variable limits the maximum data that can be sent to PHP (but it can be changed in the php.ini)
My upload function and my php file works perfectly for an input file like :
var obj=document.getElementById("inputfile");
var len = obj.files.length;
for (i=0; i<=len; i++){
upload( obj.files[i] );
}
for me the problem is the output type of your capturevideo() function or an error in captureSuccess(mediaFiles): try to change for smomething like this below :
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i].fullPath);
}
}

Image upload with different sizes in different folders using Pluploader

I want to make simple upload using plupload which takes image and convert that to multiple size like thumb,medium,full and set to their different folders location,
I have tried the code for that which run well for uploading files to different location but can't resize the image for that particular folder.
It is storing all three files with same size.
Here what I have tried is:
My Code Is:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="plupload.full.min.js"></script>
</head>
<body>
<div id="filelist">Your browser doesn't have Flash, Silverlight or HTML5 support.</div>
<br />
<div id="container">
<a id="pickfiles" href="javascript:;">[Select files]</a>
<a id="uploadfiles" href="javascript:;">[Upload files]</a>
</div>
<br />
<pre id="console"></pre>
<script type="text/javascript">
var folder = '';
var i = 0;
folder = 'full';
// Custom example logic
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: "http://localhost/plupload_new/public_html/upload.php?diretorio=" + folder,
filters: {
max_file_size: '10mb',
mime_types: [
{title: "Image files", extensions: "jpg,gif,png"},
{title: "Zip files", extensions: "zip"}
]
},
// Flash settings
flash_swf_url: '/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/plupload/js/Moxie.xap',
init: {
PostInit: function () {
document.getElementById('filelist').innerHTML = '';
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
});
},
UploadProgress: function (up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
var i = 1;
uploader.bind('BeforeUpload', function (up, file) {
if ('thumb' in file) {
if (i == 1) {
//thumb
up.settings.url = 'http://localhost/plupload_new/public_html/upload.php?diretorio=thumb',
up.settings.resize = {width: 50, height: 50, quality: 50};
} else {
// medium size
up.settings.url = 'http://localhost/plupload_new/public_html/upload.php?diretorio=medium',
up.settings.resize = {width: 400, height: 600, quality: 70};
}
} else {
up.settings.url = 'http://localhost/plupload_new/public_html/upload.php?diretorio=full',
up.settings.resize = {quality: 100};
}
uploader.bind('FileUploaded', function (up, file) {
if (!('thumb' in file)) {
file.thumb = true;
file.loaded = 0;
file.percent = 0;
file.status = plupload.QUEUED;
up.trigger("QueueChanged");
up.refresh();
} else {
i++;
file.medium = true;
file.loaded = 0;
file.percent = 0;
file.status = plupload.QUEUED;
up.trigger("QueueChanged");
up.refresh();
}
});
});
uploader.init();
</script>
</body>
</html>
Any help would be appreciated
Thank you in advance.
I have found the solution,which is a very small change to my code posted in question,the only thing i need to change is i have added attribute enabled:true in my resize parameter like,
up.settings.resize = {width: 80, height: 80, enabled: true};

HTML video player

I want to play video file from local disk in browser so I found this code. Can You tell me why it does not work? On jsfiddle it works but when i copy it into project it won't work. Also can You tell me what gives function declaration like function name(x){variables}(window).
The error I get is Uncaught TypeError: Cannot read property 'addEventListener' of null
Thanks for Your help :)
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
(function localFileVideoPlayerInit(win) {
var URL = win.URL || win.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector('input');
if (!URL) {
displayMessage('Your browser is not ' +
'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
}(window));
</script>
<h1>HTML5 local video file player example</h1>
<div id="message"></div>
<input type="file" accept="video/*"/>
<video controls autoplay></video>
</body>
</html>
The problem is, your code is running before the DOM is ready/loaded.
There's two way to fix this.
1) Move the the entire javascript code block below <video controls autoplay></video>
or
2) Use document.addEventListener("DOMContentLoaded", function() { }); like this:
<script>
document.addEventListener("DOMContentLoaded", function() {
var URL = window.URL || window.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector(("input[type=file]"));
if (!URL) {
displayMessage('Your browser is not ' +
'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
});
</script>

Categories