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
Related
this simple HTML code attached at the bottom, runs on Windows 11/Android 8 with no issues.
on Android 13, I am unable to run it.
I get -
ERROR(1): User denied Geolocation
the HTML file is located on the Galaxy S21 Internal storage and opened with Chrome.
I gave all permissions I know of, but no success.
I never got the prompt of "Allow access to your location".....
I am not an expert.
I would like to provide all the required permission in the HTML code itself, if possible.
thank you very much
<html>
<head>
<script type="text/javascript">
var x = document.getElementById("demo");
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
const crd = pos.coords;
alert(`${crd.latitude} ${crd.longitude}`);
}
function error(err) {
alert(`ERROR(${err.code}): ${err.message}`);
}
function getLocation() {
//alert("getLocation")
if (navigator.geolocation) {
//alert("getLocation true")
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
alert(position.coords.latitude + "," + position.coords.longitude)
}
</script>
</head>
<body>
<p>
Click on the button to find your location.
</p>
<button onclick="javascript: getLocation();">Get my location</button>
<div id="demo">
</div>
</body>
</html>
In some SO Questions and Answer I get to know that, with the following way one can upload files via spread Sheet to Google Drive. In that point, Is there a similar way that can be done in android ? I have searched but no luck. Lately I had used Drive Api, but I cannot overcome the consent screen problem, though I have tried several times. So, I want something with the following way. Is there any android way of the following procedure?
Code.gs:
var dropBoxId = "012345679abcdefg"; // Drive ID of 'dropbox' folder
var logSheetId = "abcdefghijklmnopqrstu123"; // Drive ID of log spreadsheet
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('InputForm.html');
}
function uploadFiles(formObject) {
try {
// Create a file in Drive from the one provided in the form
var folder = DriveApp.getFolderById(dropBoxId);
var blob = formObject.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + formObject.myName);
// Open the log and record the new file name, URL and name from form
var ss = SpreadsheetApp.openById(logSheetId);
var sheet = ss.getSheets()[0];
sheet.appendRow([file.getName(), file.getUrl(), formObject.myName]);
// Return the new file Drive URL so it can be put in the web app output
return file.getUrl();
} catch (error) {
return error.toString();
}
}
InputForm.html:
<form id="myForm">
<input type="text" name="myName" placeholder="Your full name..."/>
<input name="myFile" type="file" />
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(updateUrl)
.withFailureHandler(onFailure)
.uploadFiles(this.parentNode)" />
</form>
<div id="output"></div>
<script>
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
function onFailure(error) {
alert(error.message);
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
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.
we are having a problem with the built in browser on Android 4.0, 4.1 and 4.2 (we haven't got anything lower to test on).
The problem is that the ajax call will work perfectly on first load, you can press the run Ajax button as many times as you like and it will be fine. You can disconnect from the internet and it will work properly.
But if you exit (FULLY, make sure its not just running in the background) the browser then relaunch it, it will fail on load and on button press. It doesn't matter if you are on-line or off-line.
The error that is been returned from the ajax call is "Error" with status = 0 and readyState = 0.
When its successful you get a message back says "respose from Ajax Call" with a status = 200 and a readyState = 4.
The code works find on every other browser we have tested on Android Chrome, Firefox and Opera. on IOS 5 and 6 it works and every desktop browser we can find.
Is there something that I missing or have we found a bug in the built in browser. Any help on this would be appreciate especially if it just something stupid I have done.
We have created a test script that demonstrates this problem well I have attached it to the bottom of this message.
Thanks
Tim
test.php
<?php
function displayPage() {
?>
<!DOCTYPE html>
<html manifest="test.manifest" debug="true">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" >
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function runAjaxGet() {
var XMLHttpRequest = $.ajax({
url: "test.php",
dataType: "json",
data: "test=test",
traditional: "true",
success: function( responseData ) {
alert('good\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status );
console.log(XMLHttpRequest);
},
error: function (xhr, ajaxOptions, thrownError, responseData) {
alert('bad\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status);
console.log(XMLHttpRequest);
}
});
}
$(document).ready(function() {
runAjaxGet();
});
</script>
</head>
<body>
<button Name="Run Ajax" onclick="runAjaxGet();">Run Ajax</button>
</body>
</html>
<?php
}
function processRequests() {
header("Content-Type: application/json; charset=UTF-8" );
echo (json_encode("respose from Ajax Call"));
}
date_default_timezone_set ( "UTC" );
if (isset($_REQUEST['test'])) {
$which = $_REQUEST['test'];
} else {
$which = '';
}
switch ($which) {
case "test":
processRequests();
break;
default :
displayPage();
break;
}
?>
test.manifest
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
Just add NETWORK section with asterisk and it will work
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
NETWORK:
*
I hit this same problem and determined that when retrieved from the cache, 0 indicates success. This is likely because there is no actual http request involved since the request is resolved entirely locally.
Appcache manifest file:
CACHE MANIFEST
CACHE:
/config
Javascript:
var request = new XMLHttpRequest();
request.open('GET', '/config', false); // async=false is ok because this file will always come from AppCache
request.send(null);
// Older versions of android return 0 when ajax request retrieved from appcache
if (request.status == 200 || request.status == 0) {
return JSON.parse(request.responseText);
} else {
console.log("ERROR: config not retrievable");
throw "Attempt to retrieve config return http status " + request.status;
}
I am trying to create an offline video player that would download video content from my site for later viewing offline via an HTML5 video element. The code below works fine in Chrome for the desktop, but not on mobile (Nexus S smartphone, Nexus 7 tablet, 4.1 since only that runs chrome, which is required for the filesystem api). I am using the filesystem API that is supported by chrome on both the desktop and mobile.
I have confirmed it is correctly storing the file on the mobile device and I can retrieve the file correctly, but for some reason after retrieving the video from the localsystem chrome does not want to play the video. This is true whether I am using the html5 video element or whether I am navigating directly to the filesystem URL. When I use the html5 video element it returns the error media_err_not_supported. I have confirmed that the device can play the video if I navigate directly to it on my server (without first storing it using the filesystem api), so the issue is not a codec or video format problem. I am also using the video/mp4 mime type in both cases.
Again, this works on desktop, but not mobile. Any ideas?
Here is the code we are using:
<!DOCTYPE html >
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
var _fs;
var filename = "test3.mp4";
var diskSpaceRequired = 10 * 1024 * 1024;
$(document).ready(function () {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
function onInitFs(fs) {
_fs = fs;
getVideo(fs);
}
if (!!window.requestFileSystem) {
window.webkitStorageInfo.requestQuota(
window.webkitStorageInfo.PERSISTENT,
diskSpaceRequired, // amount of bytes you need
function () { },
function () {}
);
window.requestFileSystem(window.PERSISTENT, diskSpaceRequired, onInitFs, function () { alert('error'); });
} else {
alert('not supported');
}
$("#play").on('click', playVideo);
$("#ourVideo").on('error', function(e) { console.log('ERROR!!!', e, arguments);
console.log($("#ourVideo")[0].error);
});
});
function playVideo() {
_fs.root.getFile(filename, {}, function (fileEntry) {
$("#ourVideo").attr('src', fileEntry.toURL());
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
$("#ourVideo").get(0).play();
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
function getVideo(fs) {
fs.root.getFile(filename, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fetchResource(fileWriter);
}, errorHandler);
}, errorHandler);
}
function errorHandler(e) {
console.log('error', e);
}
function fetchResource(fileWriter) {
console.log('fetchresource');
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("GET", "http://mydomain.com/trailer.mp4", true);
xhr.onload = function(e) {
if (this.status == 200) {
var bb = new WebKitBlobBuilder();
bb.append(this.response);
var blob = bb.getBlob("video\/mp4");
fileWriter.write(blob);
} else {
console.log(this.status);
}
};
xhr.send();
}
</script>
<title>foo</title>
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source id="vidSource" type="video/mp4"/>
</video>
</body>
</html>
The problem looks like your android chrome coudn't access the android file system correctly, For that you can use nanoHttpd server for access android local files in device or sdcard.
for NanoHttpd server use this one class in your application and pass the media file location as http://localhost:8081/sdcard/(your_media_location).mp4
or get nanoHttpd from https://gist.github.com/1893396
I think this is more accurate to access sdcard files than directly calling for them
try change html part to
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source src="video1.mp4" type= "video/mp4">
<source src="video1.ogv" type= "video/ogg">
</video>
</body>
you can convert your mp4 to ogv using
http://video.online-convert.com/convert-to-ogg
and put ogv file in the same location in mp4
**for more information check out these
http://www.broken-links.com/2010/07/08/making-html5-video-work-on-android-phones/
HTML5 <video> element on Android does not play