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>
Related
This is an cordova android app. Whenever i click on the delete img button it deletes the img and goes to home page but after doing two times it deletes img stays on same page which is fine.
I don't want it go to homepage. Please help.
//Html page
<div id="main">
<div id="server-div" style="display:none;">
Server URL :<input type="text" name="server_1" id="server_1"
value="http://www.indiafastener.com/webservices/listing/upload.php" />
</div>
<div id="gallery_images_list"></div>
<br>
<div><button style="color: black" id="remImg" onclick="delImg()"
hidden>Delete Image</button>
</div>
<br><img id="loader_icon" src="images/loader.gif" style="display:none;" />
<br>
<div id="picture_msg_1" style="color:green;font-size:11px;"> </div>
<br>
<div id="image-upload" onClick="uploadImageGallery()">
<img id="pimage_1" src="images/file-upload-1.png" width="64px"
height="64px" />
</div>
<input type="hidden" name="server_image_url_1" id="server_image_url_1">
</div>
//Code
//Upload image
function uploadImageGallery() {
var imgage = document.getElementById('pimage_1');
//$("#add_company_category").val("Loading gallery...");
//$("#add_company_category").html("Loading gallery...");
$("#loader_icon").css('display', 'block');
document.getElementById('picture_msg_1').innerHTML = "";
// Get URI of picture to upload
navigator.camera.getPicture(
function(uri) {
try {
// Pick image from div
var img = document.getElementById('pimage_1');
// var img_11 = document.getElementById('pimage_11');
img.style.visibility = "visible";
img.style.display = "block";
var imageURI = uri;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('picture_msg_1').innerHTML = "Tap on picture to select image from gallery.";
return;
}
// Verify server has been entered
server = document.getElementById('server_1').value;
// server = http +'/webservices/listing/upload.php';
server = http + '/gallery-upload.php?post_id=' + localStorage.post_id_1;
console.log("Server " + server);
// alert("Server "+server);
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('picture_msg_1').innerHTML = "Upload successful: " + r.bytesSent + " bytes uploaded.";
// img.src = uri;
// img.width = 50;
// img.height = 50;
$("#gallery_images_list").append('<img src="' + uri + '" style="width:50px;" id="im">');
// shows delete img button
document.getElementById('remImg').removeAttribute('hidden');
$("#server_image_url_1").val(r.response.toString());
//$("#add_company_category").val("Submit & Finish");
//$("#add_company_category").html("Submit & Finish");
$("#loader_icon").css('display', 'none');
},
function(error) {
document.getElementById('picture_msg_1').innerHTML = "Upload failed: Code = " + error.code;
}, options);
} else {
document.getElementById('picture_msg_1').innerHTML = "Server Not Found";
}
} catch (exce) {
navigator.notification.alert(exce);
}
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('picture_msg_1').innerHTML = "No Image Found";
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
// Delete image
function delImg() {
$(function() {
document.getElementById('im').remove();
document.getElementById('picture_msg_1').innerHTML = "Image Removed";
delBtn();
});
};
// Hide Delete Button
function delBtn() {
var x = document.getElementById('gallery_images_list').childElementCount;
if (x < 1) {
document.getElementById('remImg').setAttribute('hidden');
document.getElementById('picture_msg_1').innerHTML = "";
}
};
Edit 2:
Try changing this
function delBtn() {
var x = document.getElementById('gallery_images_list').childElementCount;
if (x < 1) {
document.getElementById('remImg').setAttribute('hidden');
document.getElementById('picture_msg_1').innerHTML = "";
}
};
to this
function delBtn() {
var x = document.getElementById('gallery_images_list').childElementCount;
if (x < 1) {
$('#remImg').attr('hidden', true);
$('#picture_msg_1').html("");
}
};
Edit:
Try changing this code:
function delImg() {
$(function() {
document.getElementById('im').remove();
document.getElementById('picture_msg_1').innerHTML = "Image Removed";
delBtn();
});
};
To this.
function delImg() {
$('#im').remove();
$('#picture_msg_1').html("Image Removed");
delBtn();
};
I think you are using the remove() method wrong. You need to know the parent and remove children from that like this.
var child = document.getElementById("p1");
child.parentNode.removeChild(child);
This example was taken from here.
https://www.w3schools.com/js/js_htmldom_nodes.asp
You could also use jQuery.
$('#id').remove()
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);
}
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.
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);
I created a page to take an image or select an image from phone gallery and works normally, but i want to upload this photo selected to my server on Godaddy.
I used Cordova file transfer to upload, install file transfer by command line :
cordova plugin add https://github.com/apache/cordova-plugin-file-transfer.git
and I put a small code to upload this photo but no message alert(No error and no Success).
the code to select an image:
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';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
upload();
}
Code Upload function:
function upload() {
alert('large');
var uploadingImage = document.getElementById('largeImage');
var imgUrl = uploadingImage.src;
window.resolveLocalFileSystemURI(imgUrl, resolveOnSuccess, fsFail);
options = new FileUploadOptions();
// parameter name of file:
options.fileKey = "my_image";
// name of the file:
options.fileName = imgUrl.substr(imgUrl.lastIndexOf('/') + 1);
// mime type:
options.mimeType = "image/jpeg";
params = {val1: "some value", val2: "some other value"};
options.params = params;
ft = new FileTransfer();
ft.upload(fileuri, "http://siencelb.org/raycoding/insurance/avatar", success, fail, options);
}
function resolveOnSuccess(entry) {
fileuri = entry.toURL();
//use fileuri to upload image on server
}
function fsFail(message) {
alert("Error Message: " + message + "Error Code:" + message.target.error.code);
}
I have two buttons first to select an image and put it into div largeImage and this works.
second button to upload this image selected
Note: the alert('large') is displayed.
I solve my Error and I want to publish it
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({quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
}
;
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 = "upload.php";
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);
}
}
the PHP code of upload.php
<?php
// Directory where uploaded images are saved
$dirname = "/avatar/";
// If uploading file
if ($_FILES) {
print_r($_FILES);
mkdir ($dirname, 0777, true);
move_uploaded_file($_FILES["file"]["tmp_name"],$dirname."/".$_FILES["file"]["name"]);}
?>