I'm using this example Upload Video Phonegap to upload videos into a server which is a php script. I use exactly this code :
<!DOCTYPE html>
<html>
<head>
<title>Capture Video</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"> </script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
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: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
</head>
<body>
<button onclick="captureVideo();">Capture Video</button> <br>
</body>
</html>
Once I stop the video and I click to "Save", the app freezes and crashes just after. What can be wrong ? I have tested it on several devices because maybe some devices can't support it but still. Even if I stop the video 1 second after or 10 seconds after, the app crashes. What is weird is that the video is in the Gallery after the app crashes.
The PHP script works well because I can send it photos and it works well so I don't think the problem comes from it.
Any advice please ?
Ok I just made the changes in this answer : Phonegap video capture crashes and the app doesn't crash anymore and I can see with wireshark that something is sent to the server even if the vid isn't well received but that's an other issue.
EDIT :
Better use this function :
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
var options = new FileUploadOptions();
options.mimeType = "video/mpeg";
options.fileName = name;
options.chunkedMode = true;
ft.upload(path,
"http://192.154.23.51/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
options);
}
I can now receive succesfully the video.
Related
I am having a problem storing a file locally on an iOS (or android) device using apache cordova's "file" plugin. The problem I believe is setting the path properly.
this is the error message I get from Xcode
Could not create path to save downloaded file: The operation couldn\U2019t be completed. (Cocoa error 512.)
Here is the code where I am attempting to save the file locally:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var root;
function onDeviceReady(){
// Note: The file system has been prefixed as of Google Chrome 12:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onInitFs, errorHandler);
}
function onInitFs(fs) {
var fileURL = "cdvfile://localhost/persistant/file.png";
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://upload.wikimedia.org/wikipedia/commons/6/64/Gnu_meditate_levitate.png");
fileTransfer.download(
uri,
fileURL,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
alert('Error: ' + msg);
}
</script>
Your file path contains a typo (or a grammar error):
var fileURL = "cdvfile://localhost/persistant/file.png";
You should write it as persistent.
Correct code:
var fileURL = "cdvfile://localhost/persistent/file.png";
Check out these links :
http://cordova.apache.org/docs/en/3.4.0/cordova_plugins_pluginapis.md.html#Plugin%20APIs
https://github.com/apache/cordova-plugin-file/blob/dev/doc/index.md
http://cordova.apache.org/docs/en/3.0.0/cordova_file_file.md.html#File
First and second links provide you information about the plugin File and how to install it.
The third one show you how to use the File plugin.
Everytime you need to do something with Cordova, check if a plugin is available to do it :)
regards.
So far I have only tested this on Android, but I believe it should work as-is, or with little modification on IOS:
var url = 'example.com/foo'
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile('foo_file', {create: true, exclusive: false},
function(file_entry){
var ft = new FileTransfer()
ft.download(url, file_entry.toURL(), function(fe){
fe.file(function(f){
reader = new FileReader()
reader.onloadend = function(ev){
console.log('READ!', ev.target.result)
}
reader.readAsText(f)
})
})
}
)
})
Note that I also needed the contents of the file, so the bit at the end may be omitted if you don't need the contents at the time of downloading.
Also note that there is a far simpler method using window.saveAs but it's only available in Android 4.4.
I am developing an app with phonegap(cordova) version 3.2 and I am having problems with mysql insertion. The following codes works well in browsers (mobile or not) but, when I run the app with an android emulator or in a real device it doesn't work.
The scripts:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0-rc.1/jquery.mobile-1.4.0-rc.1.min.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#formCadastro").submit(function(){
var campoNome = new String(document.getElementById("txtNome").value);
var campoEmail = new String(document.getElementById("txtEmail").value);
var campoUsuario = new String(document.getElementById("txtUsuario").value);
var campoSenha = new String(document.getElementById("txtSenha").value);
var campoSenhaConf = new String(document.getElementById("txtSenhaConf").value);
$.ajax({
type: "POST",
url: "http://imagect.co.nf/cadastra.php",
crossDomain: true,
data: { nome: campoNome , email: campoEmail, usuario: campoUsuario, senha: campoSenha}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
window.location="index.html";
})
.fail(function(jqXHR, msg) {
alert( "Errooo:" + msg );
alert( "Errooo:" + jqXHR );
console.log("Erro chato:" + msg);
console.log(jqXHR + " " + msg);
});
});
});
</script>
The problem is that neither the fail function nor the success function happens. It seems that android ignores the ajax...
I have already tried using deviceready, pageinit, mobileinit etc. But nothing works well.
The manifest has the internet permission and the config.xml has the access origin = *.
Could someone please help me?
Thanks, sorry about my English.
I have been trying to make this work, searched google and here since Friday.
My ultimate goal is to be able take multiple pictures with a title and description for each and upload them to a server, then display on a web page.
What I have so far is: the ability to give one image a title and description, browse the gallery, find an image and select it. BUT when I do the image is uploaded along with the form, immediately. I would like to be able to do this using a submit button.
I also have a button to take an image instead, and a preview of the image on the page appears. BUT when I do take an image with the camera I do not know how to upload my form. I was able to print to the screen the image data using a div and innerHTML call... but honestly i'm so lost and do not even know where to start posting specific snippets of code. I will post the entire page as it currently exists right now....
<html>
<head>
<title>File Transfer Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function browse(){
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = document.getElementById('file_name').value + "";
params.value3 = document.getElementById('file_description').value + "";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://site.com/pages/upload.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function onFileSystemSuccess(fileSystem) {
console.log(fileSystem.name);
}
function onResolveSuccess(fileEntry) {
console.log(fileEntry.name);
}
function fail(evt) {
console.log(evt.target.error.code);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
function capturePhoto() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function onPhotoDataSuccess(imageData) {
// console.log(imageData);
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
var smallTEXT = document.getElementById('smallTEXT');
smallTEXT.style.display = 'block';
smallTEXT.innerHTML = "data:image/jpeg;base64," + imageData;
}
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Upload File</p>
<form name ="filename" id="file_name_form" action="#">
Title <br><input type="text" name="name" id="file_name" /><br>
Description <br><textarea type="text" name="description" id="file_description" /></textarea>
</form>
<button onclick="capturePhoto();">Use Camera</button> <br>
<button onclick="browse();">browse gallery</button><br>
<img style="display:none;width:160px;" id="smallImage" src="" />
<hr>
<div id="smallTEXT">ggg</div>
<button onclick"uploadPhoto();">submit</button>
</body>
According to this answer: Phonegap android unable to upload image using fileTransfer
You cannot use the URI directly....
But, it seems the uri can be used directly... (see my code below)
Edit 25-7-2013
I got this working with:
call like this:
navigator.camera.getPicture(onPhotoUriSuccess, onFailCamera, { quality: 50,
destinationType: pictDestinationType.FILE_URI });
and on succes:
function onPhotoUriSuccess(imageUriToUpload){
var url=encodeURI("http://your_url_for_the_post/");
var username='your_user';
var password='your_pwd';
var params = new Object();
params.your_param_name = "something"; //you can send additional info with the file
var options = new FileUploadOptions();
options.fileKey = "the_name_of_the_image_field"; //depends on the api
options.fileName = imageUriToUpload.substr(imageUriToUpload.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = params;
options.chunkedMode = true; //this is important to send both data and files
var headers={'Authorization':"Basic " + Base64.encode(username + ":" + password)};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(imageUriToUpload, url, succesFileTransfer, errorFileTransfer, options);
}
By the way, I use an apache webserver on the api site, I saw here, nginx could have a problem with the chunked mode:
PhoneGap chunckedMode true upload error
<!DOCTYPE html>
<html>
<head>
<title>Capture Audio,Image,Video</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
function captureSuccess2(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile2(mediaFiles[i]);
}
}
function captureSuccess3(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile3(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!");
}
function captureError2(error) {
var msg = "An error occurred during capture: " + error.code;
navigator.notification.alert(msg, null, "Uh oh!");
}
function captureError3(error) {
var msg = "An error occurred during capture: " + error.code;
navigator.notification.alert(msg, null, "Uh oh!");
}
// A button will call this function
//
function captureAudio() {
// Launch device audio recording application,
// allowing user to capture up to 2 audio clips
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2});
}
function captureImage()
{
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess2, captureError2, {limit: 2});
}
function captureVideo() {
// Launch device video recording application,
// allowing user to capture up to 2 video clips
navigator.device.capture.captureVideo(captureSuccess3, captureError3, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var win = function (r) {
alert("Code = " + r.responseCode);
alert("Bytes Sent = " + r.bytesSent);
alert("Audio Uploaded");
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
var options = new FileUploadOptions();
//options.fileKey = mediafile.file;
options.fileName = mediaFile.file;
options.mimeType = "audio/wav";
fileURL=mediaFile.fullPath;
var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://192.168.1.101:80/myfile.php"), win, fail,
options);
}
function uploadFile2(mediaFile) {
var win = function (r) {
alert("Code = " + r.responseCode);
alert("Bytes Sent = " + r.bytesSent);
alert("Image Uploaded");
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
var options = new FileUploadOptions();
//options.fileKey = mediafile.file;
options.fileName = mediaFile.file;
options.mimeType = "text/plain";
ImageURL=mediaFile.fullPath;
var ft = new FileTransfer();
ft.upload(ImageURL, encodeURI("http://192.168.1.101:80/myfile.php"), win, fail,
options);
}
function uploadFile3(mediaFile) {
var win = function (r) {
alert("Code = " + r.responseCode);
alert("Bytes Sent = " + r.bytesSent);
alert("Video Uploaded");
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
var options = new FileUploadOptions();
//options.fileKey = mediafile.file;
options.fileName = mediaFile.file;
options.mimeType = "video/mpeg";
VideoURL=mediaFile.fullPath;
var ft = new FileTransfer();
ft.upload(VideoURL, encodeURI("http://192.168.1.101:80/myfile.php"), win, fail,
options);
}
</script>
</head>
<body>
<center><h1>MCA3B Capture Session</h1></center><br><br>
<center> <button onclick="captureAudio();">Capture Audio</button> <br><br>
<button onclick="captureImage();">Capture Image</button> <br><br>
<button onclick="captureVideo();">Capture Video</button> <br>
</center>
</body>
</html>
Above is the code for capturing image,audio and video and upload it on local server.
I am turning a HTML app into a .apk using https://build.phonegap.com and everything works great appart from my file selector.
<input name="file" type="file" id="file">
I want to be able to select images only (it doesnt matter if it can select more - but its the images I am looking for) from both camera and file system..
In the web version http://carbonyzed.co.uk/websites/assent/1/photos.html this works great from my phone, but when converted to .apk, this functionality is lost, and I can't seem to find anything on here, or online relating to this issue.
At least for me, the input file doesn't work in Phonegap.
You need use the Phonegap API to get picture and select the source where come from, like photolibrary, camera or savedphotoalbum.
See more info about camera.getPicture: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#camera.getPicture
and about Camera.PictureSourceType parameter of cameraOptions method: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#cameraOptions
Ended up using the Child Browser system like so
In the head
<script src="childbrowser.js"></script>
in the body
<button class="button-big" onClick="window.plugins.childBrowser.showWebPage('URL_TO_GO_HERE',
{ showAddress: false });" style="width: 100%;">UPLOAD PHOTOS</button>
which has a standard fileuploader like
<input name="file" type="file" id="file">
then it let me select from root storage, works in phonegap 2.2 onwards on both iOS and Android OS
To capture an image I used this in the head
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
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 captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
and this in the body
<input type="button" class="button-big" style="width: 100%;" onclick="captureImage();" value="TAKE PHOTO">
copy and past and it works a dream,
Check it out in this image
any questions, just email comment,
or email me... support#carbonyzed.co.uk
I am trying to capture video in android app using phonegap, but facing problem
TypeError: Result of expression 'navigator.device.capture.captureVideo' [undefined] is not a function.
Here bellow is my code
I included following in head
<script type="text/javascript" src="js/phonegap-1.2.0.js"></script>
<script src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
function recordVideo(){
var capture = navigator.device.capture;
var options1 = { limit: 1 };
navigator.device.capture.captureVideo(captureSuccess, captureError, options1);
alert("Record");
}
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
alert(mediaFiles[i].name);
}
}
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
alert(msg);
}
</script>
And code for capturing on a button click Capture Video
But I getting this error on console
TypeError: Result of expression 'navigator.device.capture.captureVideo' [undefined] is not a function.
Please help me.
Thanks in advance.
Timir
You should add the required plugin (https://github.com/apache/cordova-plugin-media-capture/blob/master/doc/index.md)
If you are using intel xdk go to project -> plugins and permissions