android phonegap camera and image uploading - android

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.

Related

Phonegap upload error code 3

I'm developing a PhoneGap app with file upload and I'm using the following script which when I tap on upload picture it gives me an error Upload failed Code=3.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<style type="text/css">
div {border: 1px solid black;}
input {width: 100%;}
</style>
<script src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var options = new FileUploadOptions();
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<h3>PhoneGap Camera Upload Demo</h3>
<div>
<h3>Server URL for upload.php:</h3>
<input id="serverUrl" type="text" value="http://usersamplesite.com/folder" />
</div>
<br/>
<!-- Camera -->
<div>
<h3>Camera:</h3>
<b>Status:</b> <span id="camera_status"></span><br>
<b>Image:</b> <img style="width:120px;visibility:hidden;display:none;" id="camera_image" src="" />
</div>
<!-- Actions -->
<div>
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
<!-- Server pictures -->
<div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
</div>
<!-- Actions -->
<div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
</body>
</html>
I found out here that, I should use the below script to make it work, but I don't know where to put it in the script and I need help, I'm new to PhoneGap.
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
Add true in as last param of Upload Function
upload(filePath, server, successCallback, errorCallback, options, true);
Try putting options.header inside uploadPicture() rather than putting it at start of your document.
function uploadPicture() {
......
......
if(server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, success, failure, options, true);
}
}

Why does app crash when uploading video with Phonegap?

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.

Cordova FileUpload API returns error code 3

I am having problem trying to upload an image file to my local web server (hosted using wampserver) for android hybrid app built using IBM Worklight 6.2.0 with Cordova version 3.4.0. The code snippet is as below:
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
// Nothing here
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
}, {
quality: 40,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: 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 = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.168.1.4:8081/folder_name/upload2.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
</script>
<button onclick="getImage();">Upload a Photo</button>
upload2.php
<?php print_r($_FILES); $new_image_name="namethisimage.jpg" ; move_uploaded_file($_FILES[ "file"][ "tmp_name"], "folder_name/uploads/".$new_image_name); ?>
I'm getting http status 200 and an error code 3. Besides that, I also getting this error below the http status and error code error.
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:14584 from pid=4926, uid=10092 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
Is there any solution to this? Or is there a better way for me to upload the image file?
I've added the following to AndroidManifest.xml
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am not sure what's the issue here. My code just works suddenly, even with AngularJS. I will just share my working code here, if others might want to refer.
main.js
$scope.getImage = function() {
// Retrieve image file location from specified source
navigator.camera.getPicture(onSuccess, function(message) {
alert('get picture failed');
},{
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function onSuccess(imageURI) {
$scope.image = imageURI;
};
function uploadPhoto(image) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName= $scope.imageName;
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(image, encodeURI(ipaddress_to_your_server/root_folder/upload.php), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
upload.php
<?php
print_r($_FILES);
$image_name = $_FILES['file']['name'];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$image_name);
?>
You will just need to call the $scope.getImage function in html to open the device's photo library.
Based on the last image, it seems that you solved this somehow - you should share it as an answer.
Regardless,
Why is there PHP code in your code snippet? Is this code snippet originating from your Worklight-based app? You cannot have there PHP... This is a mobile app, running in your device, not on your server. There is nothing there that will interpret that code.
The following should not be used in your app, because Cordova is part of the Worklight framework and this check is done internally. Instead, your code should sit inside the wlCommonInit() function in main.js, or be called from there.
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
// Nothing here
}
I suspect that is why nothing works for you. Try to use AJAX to make the request to the server, to receive the sent image and store it in your web server.

How do you store a file locally using Apache Cordova 3.4.0

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.

Cordova-2.1.0 capture and upload photo to server

I'm new here and have a problem in last week:
I made an app in phonegap(cordova2.1.0) and this is the code:
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
HTML code:
Image:
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
well: part of this code is not mine.
QUESTION
there is no error alert
the alert says everything was done. image uploaded and the bytes
in my msql the image has no the extension(.jpg) only the name
and in the images folder theres nothing uploaded
i whitelisted everything,
can anibody help me?
I don't know wat else to do..
thanks in advance
by the way in eclipse log everithing shows ok too,
in android 2.3 actual phone the same thing, but the image is not there..

Categories

Resources