PhoneGap: Storing/Retrieving Image Using LocalStorage - javascript

I'm new to PhoneGap and I'm trying to create an application that will include a feature that will take a photo and store the file path(?) in local storage so that the image can then be retrieved along with other data. I know that local storage doesn't allow a user to store a large amount of data but for this app I'm just looking to use local storage only for now. Here is a dulled down version of my local storage saving the text data:
$(function () {
$('[type=submit]').on('click', function (e) {
userList.addUser(
$('#name').val(),
$('#address').val(),
$('#message').val(),
);
$('input:text').val('');
return false;
});
$('#users').on('click', '.delete', function (e) {
userList.deleteUser(parseInt($(this).parent().find('.key').text()));
return false;
});
$('#users').on('click', '.update', function (e) {
var name = $(this).parent().find('.name').text();
var address = $(this).parent().find('.address').text();
var type = $(this).parent().find('.message').text();
var key = parseInt($(this).parent().find('.key').text());
userList.updateUser(name,address,message,key);
return false;
});
userList.open();
});
userList = {};
userList.open = function() {
this.list = { };
if (localStorage.userList) {
this.list = JSON.parse(localStorage.userList);
}
userList.getAllUsers();
};
userList.addUser = function(name,address,message) {
console.log(arguments.callee.name, arguments);
key = new Date().getTime();
this.list[key] = {
'name':name,'address':address,'message':message
};
localStorage.userList = JSON.stringify(this.list);
this.getAllUsers();
};
userList.getAllUsers = function() {
$('#users').html('');
for (var key in this.list) {
renderUser(key, this.list[key]);
}
};
userList.deleteUser = function(id) {
console.log(arguments.callee.name, arguments);
delete this.list[id];
localStorage.userList = JSON.stringify(this.list);
this.getAllUsers();
};
userList.updateUser = function(name,address,message,key) {
console.log(arguments);
this.list[key]['name'] = name;
this.list[key]['address'] = address;
this.list[key]['message'] = message;
localStorage.userList = JSON.stringify(this.list);
this.getAllUsers();
};
function renderUser(key,value) {
console.log(arguments);
var li = '<li><span class="name" contenteditable="true">'+value.name+'</span> ';
li += '<span class="address" contenteditable="true">'+value.address+'</span> ';
li += '<span class="message" contenteditable="true">'+value.message+'</span> ';
li += '[Update] ';
li += '[Delete]<span class="key">'+key+'</span></li>';
$('#users').append(li);
}
...and here is the code I have that takes an photo and stores the photo in the users photo album...
var pictureSource;
var destinationType;
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL, saveToPhotoAlbum: true});
}
function onFail(message) {
alert('Failed because: ' + message);
}
If anyone could shed some light on how I can retrieve an image by perhaps storing its file path along with some other text data I'd be extremely grateful! I've looked all over for a helpful tutorial but nothing seems to work out for my problem.
Thank you!! (PS. Sorry for this long post!)

var pictureSource;
var destinationType;
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
photo = "data:image/jpeg;base64," + imageData;
localStorage.setItem('photo', photo);
}
function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail,
{
quality: 20,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
encodingType: Camera.EncodingType.JPEG
});
}
function onFail(message) {
alert('Failed because: ' + message);
}

Related

Storing image file in server file system using Image URI

I am getting URL from this Cordova Camera API and I am posting to WEBAPI. I tried with base64 but it increases the image size when I post it in server.
Please find my code below and suggest me how to save file to server.
//WEB API//
public IHttpActionResult UpdateUserDetails(ImageModel model)
{
try
{
if (model.ImageBase64 != "")
{
var PicDataUrl = "";
string ftpurl = "ftp://xxx.xxxxx.xxxx/";
var username = "xxx";
var password = "xxxxx";
string UploadDirectory = "xxxx/xx";
string FileName =model.ImageFileName;
String uploadUrl = String.Format("{0}{1}/{2}", ftpurl, UploadDirectory,FileName);
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
req.Proxy = null;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential(username, password);
req.EnableSsl = false;
req.UseBinary = true;
req.UsePassive = true;
// I am getting URI path like below and need to save this file in server
model.ImageBase64 = C:\Program Files (x86)\IIS Express\services5.jpg
byte[] data =Convert.FromBase64String(model.ImageBase64);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
}
}
// I am getting URL from this Cordova Camera API and I am posting to WEBAPI
function onSuccessEdituserProfileGallery(imageData) {
console.log(imageData);
var smallImage
smallImage = document.getElementById('EdituserProfileImage');
smallImage.src = imageData;
customerImgData =smallImage.src;
return customerImgData;
}
usually i do this:
Back End:
[HttpPost]
[Route("Upload/Image")]
public async Task<IHttpActionResult> UploadImg()
{
try
{
#region VAR
if (!Directory.Exists(HttpContext.Current.Server.MapPath(string.Concat("~", Constant.Application.User_Cropped_Image_Directory)))) ;
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(string.Concat("~", Constant.Application.User_Cropped_Image_Directory)));
string mapPath = HttpContext.Current.Server.MapPath(string.Concat("~", Constant.Application.User_Cropped_Image_Directory));
HttpRequestMessage request = this.Request;
String fileName = "";
#endregion VAR
#region SPLIT
// Get base64 string from POST
var base64String = request.Content.ReadAsStringAsync().Result;
// SPLIT Content from unecessary data
var split = base64String.Split(',');
var strings = split[1].Split('-');
#endregion SPLIT
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(strings[0]);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
if (!Directory.Exists(String.Concat(mapPath, fileName).ToLowerInvariant()))
Directory.CreateDirectory(String.Concat(mapPath, fileName).ToLowerInvariant());
fileName = GenericUtils.GetFileNameWithExt(image).ToLowerInvariant();
//name = String.Concat("croppedImage_", fileName);
image.Save(String.Concat(mapPath, fileName).ToLowerInvariant());
return Ok(new { data = String.Concat(Constant.Application.User_Cropped_Image_Directory, fileName).ToLowerInvariant() } );
}
catch (Exception ex)
{
_logger.LogException(ex);
return null;
}
}
Ionic (js):
$scope.takeFromCamera = function () {
document.addEventListener("deviceready", function () {
var options = {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
correctOrientation: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 600,
targetHeight: 600,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true
};
if ($cordovaCamera)
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
//Image in Base64 to send to server for web profile
// var imgRaw = "data:image/jpeg;base64," + imageData;
$upload.upload({
url: enviroment.apiUrl + 'api/Upload/Image',
fields: { 'base64String': $scope.imgURI },
file: $scope.imgURI
}).success(function (data, status, headers, config) {
$scope.imageName = data.data;
$rootScope.$broadcast("update-img", { img: $scope.imageName });
});
}, function () {
$cordovaToast.show('Camera non Disponibile Si Prega di Riprovare piu tardi!', 'long', 'center');
});
}, false);
};

Length of uploaded couchDB attachment always 0 Bytes

So...I'm new to all this stuff and I'm developing an app for android with AngularJS and Ionic Framework and try to upload an audiofile I have recorded with the cordova capture Plugin like this:
// gets called from scope
$scope.captureAudio = function() {
var options = { limit: 1, duration: 10 };
$cordovaCapture.captureAudio(options).then(function(audioData) {
uploadFile(documentID, audioData);
}, function(err) {
console.log('error code: ' + err);
});
};
var uploadFile = function (document, file) {
var baseUrl = 'urltomydatabase';
var name = encodeURIComponent'test.3gpp'),
type = file[0].type,
fileReader = new FileReader(),
putRequest = new XMLHttpRequest();
$http.get(baseUrl + encodeURIComponent(document))
.success(function (data) {
putRequest.open('PUT', baseUrl + encodeURIComponent(document) + '/' + name + '?rev=' + data._rev, true);
putRequest.setRequestHeader('Content-Type', type);
fileReader.readAsArrayBuffer(file[0]);
fileReader.onload = function (readerEvent) {
putRequest.send(readerEvent);
};
putRequest.onreadystatechange = function (response) {
if (putRequest.readyState == 4) {
//success - be happy
}
};
})
.error(function () {
// failure
});
};
How the file looks in the console.log:
Playing the recorded file on the device works nice.
But everytime I upload the recording and the upload has finished, the uploaded attachment inside the document has the length '0' in the couchDB.
How the created file looks in the database after the upload:
What am I doing wrong?
EDIT: I just found out, when I upload an image, passed from this function as blob, it works well:
function upload(imageURL) {
var image = new Image();
var onload = function () {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
canvas.toBlob(function (blob) {
uploadFile(documentID, blob);
});
};
image.onload = onload;
image.src = imageURL;
}
So maybe the solution is creating a blob from the audiofile? But everytime I try it, my blob has the size of 0 bytes even before uploading it and I don't find somewhere a great explanation of how to convert a MediaFile object to blob...
It looks like your code does not send the content of your file as multipart attachment. To see what is really send to couchdb, capture the traffic with wireshark (https://www.wireshark.org/) or such.
This thread brought me to the solution, PouchDB purifies it. Now my upload function looks like this and can handle every file format
// e.g capture Audio
$scope.captureAudio = function () {
var options = {limit: 1, duration: 10};
$cordovaCapture.captureAudio(options).then(function (audioData) {
uploadFile(documentID, audioData, 'audio');
}, function (err) {
console.log('error code: ' + err);
});
};
var uploadFile = function (id, file, mediatype) {
var fileName = makeID();
if (mediatype == 'image') var name = encodeURIComponent(fileName + '.jpg');
if (mediatype == 'audio') var name = encodeURIComponent(fileName + '.3gpp');
if (mediatype == 'video') var name = encodeURIComponent(fileName + '.3gp');
db.get(id).then(function (doc) {
var path = file.fullPath;
window.resolveLocalFileSystemURL(path, function (fileEntry) {
return fileEntry.file(function (data) {
var reader = new FileReader();
reader.onloadend = function (e) {
var blob = b64toBlobAlt(e.target.result, file.type);
if (blob) {
db.putAttachment(id, name, doc._rev, blob, file.type).then(function () {
if (mediatype == 'video' || mediatype == 'image') getMedia();
if (mediatype == 'audio') $scope.audios.push(source);
});
}
};
return reader.readAsDataURL(data);
});
});
});
};
// creating the blob from the base64 string
function b64toBlobAlt(dataURI, contentType) {
var ab, byteString, i, ia;
byteString = atob(dataURI.split(',')[1]);
ab = new ArrayBuffer(byteString.length);
ia = new Uint8Array(ab);
i = 0;
while (i < byteString.length) {
ia[i] = byteString.charCodeAt(i);
i++;
}
return new Blob([ab], {
type: contentType
});
}

Redirect after file upload in phonegap

My phonegap upload script works perfectly. After the upload you get a message "Please wait redirecting". I want to know how to add a redirection script so immediately after upload, it redirects to another page
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)+'.jpg';
options.mimeType="image/jpeg";
options.chunkedMode = false;
options.params = {
filename: window.localStorage.setItem("key", options.fileName)
}
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, "http://myphonegap.com/upload.php", function(r) {
document.getElementById('camera_status').innerHTML = "Please wait redirecting";
}, 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);
}
Just do the page transition at the end of the success function. E.g after This line:
document.getElementById('camera_status').innerHTML = "Please wait redirecting";
Do:
window.location.href = "otherpage.html"
Or:
$('page1_div').hide();
$('page2_div').show();
Etc.

Multiple Image upload to server in Cordova

I tried uploading multiple Images to server.
I am able to click images and display it in block but not able to transfer it to server. Error I am getting is 04-02 10:35:41.984: I/chromium(23772): [INFO:CONSOLE(104)] "Uncaught TypeError: Cannot call method 'lastIndexOf' of undefined", source: file:///android_asset/www/index.html (104)
Code:
<!DOCTYPE html>
<html>
<head>
<title>Submit form</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
/* function onPhotoURISuccess(imageURI) {
// Show the selected image
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageURI;
}*/
function onPhotoDataSuccess1(imageData) {
var smallImage1 = document.getElementById('smallImage1');
smallImage1.style.display = 'block';
smallImage1.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoDataSuccess2(imageData) {
var smallImage2 = document.getElementById('smallImage2');
smallImage2.style.display = 'block';
smallImage2.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoDataSuccess3(imageData) {
var smallImage3 = document.getElementById('smallImage3');
smallImage3.style.display = 'block';
smallImage3.src = "data:image/jpeg;base64," + imageData;
}
function capturePhoto1() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess1, onFail, { quality: 20,
destinationType: destinationType.DATA_URL,
});
}
function capturePhoto2() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess2, onFail, { quality: 20,
destinationType: destinationType.DATA_URL,
});
}
function capturePhoto3() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess3, onFail, { quality: 20,
destinationType: destinationType.DATA_URL,
});
}
// A button will call this function
/*
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 20,
destinationType: destinationType.FILE_URI,
sourceType: source });
}*/
//selected photo URI is in the src attribute (we set this on getPhoto)
var imageURI1 = document.getElementById('smallImage1').getAttribute("src");
var imageURI2 = document.getElementById('smallImage2').getAttribute("src");
var imageURI3 = document.getElementById('smallImage3').getAttribute("src");
if (!imageURI1) {
alert('Please select an image first.');
return;
}
var items = [imageURI1,imageURI2,imageURI3];
$.each(items,function(){
uploadPhoto($(this));
});
function uploadPhoto(imageURI) {
//set upload options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
workplace: document.getElementById("workplace").value
}
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://www.xyz.co/AppData/upload.php"), win, fail, options);
}
// Called if something bad happens.
//
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>
<form id="regform">
<input type="button" onclick="capturePhoto1();" value="Capture Photo"><br>
<img style="display:none;width:60px;height:60px;" id="smallImage1" src="" />
<input type="button" onclick="capturePhoto2();" value="Capture Photo"><br>
<img style="display:none;width:60px;height:60px;" id="smallImage2" src="" />
<input type="button" onclick="capturePhoto3();" value="Capture Photo"><br>
<img style="display:none;width:60px;height:60px;" id="smallImage3" src="" />
First Name: <input type="text" id="firstname" name="firstname"><br>
Last Name: <input type="text" id="lastname" name="lastname"><br>
Work Place: <input type="text" id="workplace" name="workPlace"><br>
<input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
</form>
</body>
</html>
I guess there's some problem in function uploadPhoto(). Foreach loop is not handling imageURI properly.
What can be the solution?
Please see if it help for you. your uploadPhoto function has the imageURI parameter but you are calling the uploadPhoto() function in button click without passing any parameter. your function should be
function intUpload(){
var imageURI1 = document.getElementById('smallImage1').getAttribute("src");
var imageURI2 = document.getElementById('smallImage2').getAttribute("src");
var imageURI3 = document.getElementById('smallImage3').getAttribute("src");
if (!imageURI1) {
alert('Please select an image first.');
return;
}
var items = [imageURI1,imageURI2,imageURI3];
$.each(items,function(){
uploadPhoto($(this));
});
}
function uploadPhoto(imageURI) {
//set upload options
var d = new Date();
var options = new FileUploadOptions();
options.fileKey = "vImage" + d.getTime();
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
workplace: document.getElementById("workplace").value
};
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://www.xyz.co/AppData/upload.php"), win, fail, options);
}
and your button click should be
<input type="button" id="btnSubmit" value="Submit" onclick="intUpload();">
also your html page doesn't include any jquery file but you are using $.each jquery function. please include the jquery file
<script type="text/javascript" charset="utf-8">
///// photo for 1 photo
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
var x=0;
function onPhotoDataSuccess(imageURI)
{
x++;
// Uncomment to view the base64-encoded image data
console.log(imageURI);
// Get image handle
//
var y = 'smallImage'+x;
var smallImage = document.getElementById(y);
smallImage.src = "data:image/jpeg;base64," + imageURI;
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
//var fso=new ActiveXObject("Scripting.FileSystemObject");
//fso.CopyFile("data:image/jpeg;base64," + imageURI,"file:///storage/sdcard/DCIM/");
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI)
{
x++;
// Uncomment to view the base64-encoded image data
console.log(imageURI);
//alert(imageURI);
// Get image handle
//
var y = 'smallImage'+x;
var smallImage = document.getElementById(y);
//alert(smallImage);
smallImage.src = imageURI;
// Unhide image elements
//
smallImage.style.display = 'block';
//alert(smallImage.src)
}
// A button will call this function
//
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 });
}
// A button will call this function
//
function capturePhotoEdit()
{
// 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 });
}
// A button will call this function
//
function getPhoto()
{
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
allowEdit: true,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM
});
/* window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
alert('Image URI: ' + results[i]);
}
}, function (error) {
console.log('Error: ' + error);
}, {
maximumImagesCount: 4,
width: 800
}*/
}
// Called if something bad happens.
//
function onFail(message)
{
alert('Failed because: ' + message);
}
</script>

File upload button is still not working in Cordova / Phonegap Project

Iam unable to upload pictures to a webserver with PHP backend.
My cordova camera script is able to taking the picture and show the picture in small size. But it is not able to upload an image. I dont no why. I call the function photoUpload(); and set the a onClick-event in the button like
<button class="camera-control" onclick="photoUpload();">UPLOAD</button>
Here is my JavaScript, whats wrong with it?
var pictureSource;
var destinationType;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onCapturePhoto(fileURI) {
$("#cameraPic").attr("src", fileURI);
var win = function (r) {
clearCache();
retries = 0;
navigator.notification.alert(
'',
onCapturePhoto,
'Der Upload wurde abgeschlossen',
'OK');
console.log(r);
}
var fail = function (error) {
navigator.notification.alert(
'Bitte versuchen Sie es noch einmal.',
onCapturePhoto,
'Ein unerwarteter Fehler ist aufgetreten',
'OK');
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
if (retries == 0) {
retries ++
setTimeout(function() {
onCapturePhoto(fileURI)
}, 1000)
} else {
retries = 0;
clearCache();
alert('Fehler!');
}
}
function photoUpload() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
}
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI
});
}
function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message) {
alert('Failed because: ' + message);
}
Look your function photoUpload is located in the function onCapturePhoto! you need to move function photoUpload on the top level.
window.photoUpload = function() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
And the better way to do it like:
<button class="camera-control" id="photoUploadButton;">UPLOAD</button>
document.getElementById("photoUploadButton").addEventListener("click", photoUpload);

Categories