I am a phonegap newbie. I am trying to read and image file from sdcard in android using
phonegap official tutorial. The problem is that the image is not being displayed instead a question mark appears in its place.
My Code:
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
document.getElementById("test").innerHTML="onready about to request";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("1.jpg", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
edit:
Using API 16 and min-sdk8
"smallImage" is a tag it's working fine with onphotodatasuccess. So, camera is not a problem here. Everything related to camera functions is ok. Reading from sdcard is posing a problem at the assignment statement.
document.getElementById("smallImage").src = reader.readAsDataURL(file); if I add this i get the string and unknown chromium error -6, else i see the usual image converted string.
Thanks
Here is a working example :
EDITED:
<!DOCTYPE html>
<html>
<head>
<title>Pick Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);
}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("1.jpg", {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = evt.target.result;
};
reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
This will allow you to pick any specified image from sdcard.
Hope this helps you.
Thanks.
try this:
<script>
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
//This file have to exist
var location= "file:///storage/emulated/0/DCIM/Camera/20141105_124208.jpg";
window.resolveLocalFileSystemURL(location, function(oFile) {
oFile.file(function(readyFile) {
var reader= new FileReader();
reader.onloadend= function(evt) {
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = evt.target.result;
};
reader.readAsDataURL(readyFile);
});
}, function(err){
console.log('### ERR: filesystem.directoryUp() - ' + (JSON.stringify(err)));
});
</script>
Related
I'm developing an application that will have to send images to an external server, downloaded and installed the file-transfer , however it stopped working appearing error 3, I am running xampp on my local network, below is my code, I took it from the plugin documentation
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>File Transfer Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
// Retrieve image file location from specified source
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 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.168.0.105/upload/index.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
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);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Upload File</p>
</body>
</html>
PHP:
<?php
$new_image_name = strtolower($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$new_image_name);
Add the header object to option once.
Solution from here
options.headers = {
Connection: "close"
}
I am facing a problem here for my code. Whenever I put in my function uploadPhoto, the function capturePhotoWithFile would not work(I pressed the button but nothing happened). However when I remove the function uploadPhoto, the function capturePhotoWithFile would work again(I could pressed the button and take a photo).
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1"/>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoFileSuccess(imageData) {
console.log(JSON.stringify(imageData));
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
}
function capturePhotoWithFile() {
navigator.camera.getPicture(onPhotoFileSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onFail(message) {
alert('Failed because: ' + message);
}
function uploadPhoto() {
var imageData = document.getElementById('smallImage').getAttribute("src");
if (!imageData) {
alert('Please select an image first.');
return;
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageData.substr(imageData.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
}
var ft = new FileTransfer();
ft.upload(imageData, encodeURI("uploadtest.php"), win, fail, options);
}
function onFail(message) {
console.log('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert("Response =" + r.response);
console.log("Sent = " + r.bytesSent);
}
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);
}
</script>
</head>
<body>
<button onclick="capturePhotoWithFile();">Capture Photo</button> <br>
<button onclick="uploadPhoto();">Upload</button> <br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
Try this way :
function getPictureFromCamera(){
navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType:Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
$('#camera-image').css({'background-image': 'url('+imageURI+')', 'background-size': '100%'});
}
function onFail(message) {
console.log('Failed to get an image');
}
}
function getPictureFromGallery(){
navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY });
function onSuccess(imageURI) {
$('#camera-image').css({'background-image': 'url('+imageURI+')', 'background-size': '50%'});
}
function onFail(message) {
console.log('Failed to get an image');
}
}
OutPut:
How do I write html to a text file using Phonegap? I'm trying to follow the example in the API documentation. The file creating works but I can't get console.log to work.
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log($("h1"));
};
}
function fail(error) {
console.log(error.code);
}
<body>
<h1>Example</h1>
<p>Write File</p>
</body>
Use "document.write" instead. It worked for me.
try to use
Log.d("info", "YOUR_TEXT");
I have example.txt file sdcard and I want to display it using phone gap.I am very new to android and phone gap please help.
Here is my example.txt file:
<h2>This file is in sdcard</h2>
Here is my phonegap.java
package com.example.phonegap;
import org.apache.cordova.DroidGap;
public class Phonegap extends DroidGap{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/myfile.html");
}
}
and here is the myfile.html in www:
<!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("file:///sdcard/example.txt", {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
Change this line:
fileSystem.root.getFile("file:///sdcard/example.txt", {create: true}, gotFileEntry, fail);
to be this:
fileSystem.root.getFile("example.txt", {create: false}, gotFileEntry, fail);
assuming that the file you want to read is "example.txt" and is located in the /sdcard folder.
I also encountered the same problem. I don't think the API document in Phonegap is right, so i referred JavaScript:the definitive guide, I found two key points:
the location of the file I am ready to read.
--> I found the default parent path is : /mnt/sdcard. So "/mnt/sdcard/temp/test.txt" file was written as fileSystem.root.getFile("temp/test.txt", null, gotFileEntry, fail)
after reader.readAsText(file), just using element.innerHTML = reader.result can't display the result in HTML file.
so I add a callback:
reader.onload = function(){
element.innerHTML = reader.result
}
After adjusting the two parts, my code works!
StackOverflow has very strict upload format policy, so I can't upload the exact code. But you can contact me to ask for the code.
I assume that the example.txt is at the root of SD card(Not resides in a folder). Then change following of your code,
function gotFS(fileSystem) {
fileSystem.root.getFile("file:///sdcard/example.txt", {create: true}, gotFileEntry, fail);
}
to
function gotFS(fileSystem) {
fileSystem.root.getFile("example.txt", {create: true}, gotFileEntry, fail);
}
And try by using alert in the below function,
function readAsText(file) {
alert("readAstext");
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
alert("content : "+evt.target.result);
};
reader.readAsText(file);
}
If that is not work, please add below code to your body tag in HTML
<body onload='onLoad();'>
Let me know issues you may faced.
Thanks,,
I tried writing/reading a file in phonegap+android, here is the set up:
$(document).ready(function() {
document.addEventListener("deviceready", deviceready, true);
$(document).bind("deviceready", function(){
//writeFile();
//readFile();
});
});
function deviceready() {
writeFile();
readFile();
}
// This is just to do this.
function readFile() {
var d = navigator.file.read('/sdcard/foo.xml', success(), fail());
console.warn(d);
}
function writeFile() {
navigator.file.write('/sdcard/foo.xml', "This is a test of writing to a file",
success(), fail());
}
But on the emulator for Android 2.2, I got the following error message:
08-06 14:21:29.428: INFO/Web Console(936): Error in success callback: Network Status1 = TypeError: Result of expression 'navigator.file' [undefined] is not an object. at file:///android_asset/www/phonegap.0.9.6.js:649
What could be missing and what could be tried?
This also works in Android 2.2. You call the load(); function from body's onLoad, and writeFileFromSDCard(string) from some button's onClick, passing as parameter the string you want to write in the file.
<script type="text/javascript" charset="utf-8">
// Event listener
function load() {
document.addEventListener('deviceready', init, false);
}
// Called when device is ready - Do nothing
function init() {
}
// Called to write file to card
function writeFileFromSDCard(param) {
var writer = new FileWriter("/sdcard/write.txt");
writer.write(param + "\n", false);
alert("file Written to SD Card");
}
</script>
I would try using the FileReady and FileWriter APIs.
http://docs.phonegap.com/phonegap_file_file.md.html#FileReader
Here is what I came up with based on several links. I had been searching to do this as well. I used this site as a reference http://www.digitalnoiz.com/mobile-development/mobile-file-explorer-with-phonegapcordova-and-jquery-mobile-part-1/ as well as the Phonegap document api references
function displayMessage(msg)
{
navigator.notification.alert(msg);
}
function loadDirectories(fileSystem)
{
directoryEntry = fileSystem.root;
var directoryReader = directoryEntry.createReader();
directoryReader.readEntries(function(entries){
var sOutput = "";
for(var i=0; i < entries.length; i++)
{
if(!entries[i].isDirectory)
{
fileSystem.root.getFile(entries[i].name,null,gotFileEntry,fail);
}
}
//displayMessage(sOutput);
},fail);
}
function gotFileEntry(fileEntry)
{
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(evt){
displayMessage(evt.target.result);
};
reader.readAsText(file);
},fail);
}
function failFile(evt)
{
displayMessage(evt.target.error.code);
}
function fail(error)
{
displayMessage("Failed to list directory contents: " + error.code);
}
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, loadDirectories, fail);
}
The following works for me on Android with phonegap-1.0.0:
<script type="text/javascript" charset="utf-8" src="css-js/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
var path = "readme.txt";
fileSystem.root.getFile(path, {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.write("some sample text");
</script>