trying to save an image from Phonegap camera - image

I have this code which should get the base64 of the captured image, then save it as a jpg into the devices SD card, under the foler MyAppFolder. However it wont work and i cannot figure out why
<html>
<head>
<script src=../cordova.js></script>
<script>
// A button will call this function
//
function capturePhoto() {
sessionStorage.removeItem('imagepath');
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onPhotoDataSuccess(imageURI) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var imgProfile = document.getElementById('imgProfile');
// Show the captured photo
// The inline CSS rules are used to resize the image
//
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1){
getLocation();
}
movePic(imageURI);
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
function movePic(file){
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
//Callback function when the file system uri has been resolved
function resolveOnSuccess(entry){
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
//The folder is created if doesn't exist
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory) {
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
//Callback function when the file has been moved successfully - inserting the complete path
function successMove(entry) {
//Store imagepath in session for future use
// like to store it in database
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error) {
alert(error.code);
}
</script>
</head>
<body>
<button onclick="capturePhoto()">Take photo</button>
<img src="" id="imgProfile" style=position:absolute;top:0%;left:0%;width:100%;height:100%;>
</body>
</html>
when the button is pressed, the camera doesnt launch.

I solved it as follow. It might help you:
function capturePhoto() {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoSuccess, function(message) {
alert('Image Capture Failed');
}, {
quality : 40,
destinationType : Camera.DestinationType.FILE_URI
});
}
function onPhotoSuccess(imageURI) {
var gotFileEntry = function(fileEntry) {
alert("Default Image Directory " + fileEntry.fullPath);
var gotFileSystem = function(fileSystem) {
fileSystem.root.getDirectory("MyAppFolder", {
create : true
}, function(dataDir) {
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
// copy the file
fileEntry.moveTo(dataDir, newFileName, null, fsFail);
}, dirFail);
};
// get file system to copy or move image file to
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem,
onFail);
};
// resolve file system for image
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, fsFail);
// file system fail
var onFail = function(error) {
alert("failed " + error.code);
};
var dirFail = function(error) {
alert("Directory" + error.code);
};

The button wont get clicked because your image src is overlapping it.
Change the position of image src and your code shall work fine

Related

How to get file from Image in NativeScript and upload it to server

I have an component that displays and image either taken by camera or selected from gallery. The point is when a user clicks the upload button i should send that Image to my server, but i am having difficulties extracting the file from the Image component.
<Image ref="profileImage" borderRadius="100" width="150" height="150" marginTop="20" stretch="aspectFill" :src="profileImage" />
And i have two functions for picking an image or capturing one
capture: function() {
var isAvailable = camera.isAvailable();
if (isAvailable) {
var options = {
width: 300,
height: 300,
keepAspectRatio: false,
saveToGallery: false,
cameraFacing: 'front'
};
var self = this;
var imageModule = require("tns-core-modules/ui/image");
camera.requestPermissions().then(
function success() {
camera.takePicture(options)
.then(function(imageAsset) {
self.profileImage = imageAsset;
}).catch(function(err) {
console.log("Error -> " + err.message);
});
},
function failure() {
// permission request rejected
}
);
}
},
pick() {
var self = this;
let context = imagepicker.create({
mode: 'single',
mediaType: 'image'
});
context.authorize()
.then(function() {
return context.present();
})
.then(selection => {
selection.forEach(selected => {
self.profileImage = selected;
});
}).catch(function(e) {
console.log('error in selectPicture', e);
});
},
What i need to do next is get the uploaded image and send it to server but i can't seem to find an options for that, i have the src of the and that's it in this case...
You can simply get ImageSource from ImageAsset and write it as file in data or temp directory, then upload it to server.
const imageSourceModule = require("tns-core-modules/image-source");
const fileSystemModule = require("tns-core-modules/file-system");
function uploadAsset(asset) {
imageSourceModule.fromAsset(asset)
.then(function(imageSource) {
var folderDest = fileSystemModule.knownFolders.documents();
var pathDest = fileSystemModule.path.join(folderDest.path, "test.png");
var saved = imageSource.saveToFile(pathDest, "png");
if (saved) {
console.log("Image saved successfully!");
// Now file is written at path `pathDest`
}
}).catch(function(err) {
console.log(err);
});
}
....
uploadAsset(profileImage);
Learn more at docs

How to access the image data after dropping an image from the html-part of a webpage onto a canvas?

This is a follow up question to
How to drop texts and images on a canvas? (Firefox 41.0.1)
I simply can't find out how to access the image data of the image I dropped onto the canvas. I tried things like data = event.dataTransfer.getData("image"), but that all doesn't work.
function addDragNDropToCanvas() {
document.getElementById('canvas').addEventListener("dragover", function(event) { event.preventDefault();}, false);
//handle the drop
document.getElementById('canvas').addEventListener("drop", function(event) {
event.preventDefault();
console.log('something is dropped on the object with id: ' + event.target.id);
// var directData=event.dataTransfer.getData("image");
console.log(event);
}, false);
}
There surely is the image-data somewhere incorporated in the drop-event data? Isn't it???
(The image doesn't have an own id-attribute.)
Your user might do one (or both) of these two drags:
Drag an img element from your webpage onto the canvas, or
Drag an image file from your local drive onto the canvas.
If the image is being dragged from your webpage:
Listen for the dragover, drop, and optionally the dragenter events.
When handling all 3 events, tell the browser you're handling the event with event.preventDefault and optionally event.stopPropagation.
In the drop handler, get event.dataTransfer.getData('text/plain') which fetches the.src` of the image that was dropped.
Create a new Image() object using the .src and drawImage to the canvas.
If the image is being dragged from your local drive:
1 & 2. Listen & handle the same events as in the webpage code.
Fetch the local image file(s) that the user dropped which have been placed in event.dataTransfer.files.
Create a FileReader and read each image file. The FileReader.readAsDataURL method will return an image URL that you can use as a .src for an Image object.
drawImage each new image to the canvas.
Here's example code that allows both:
window.onload=function(){
// canvas related vars
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// dropZone event handlers
var dropZone=document.getElementById("canvas");
dropZone.addEventListener("dragenter", handleDragEnter, false);
dropZone.addEventListener("dragover", handleDragOver, false);
dropZone.addEventListener("drop", handleDrop, false);
//
function handleDragEnter(e){e.stopPropagation(); e.preventDefault();}
//
function handleDragOver(e){e.stopPropagation(); e.preventDefault();}
//
function handleDrop(e){
e.stopPropagation();
e.preventDefault();
//
var url=e.dataTransfer.getData('text/plain');
// for img elements, url is the img src so
// create an Image Object & draw to canvas
if(url){
var img=new Image();
img.onload=function(){ctx.drawImage(this,0,0);}
img.src=url;
// for img file(s), read the file & draw to canvas
}else{
handleFiles(e.dataTransfer.files);
}
}
// read & create an image from the image file
function handleFiles(files) {
for (var i=0;i<files.length;i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)){continue;}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
var reader=new FileReader();
reader.onload=(function(aImg){
return function(e) {
aImg.onload=function(){
ctx.drawImage(aImg,0,0);
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
}; // end $(function(){});
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<!doctype html>
<html>
<body>
<h4>Drag an image from below onto the canvas, or<br>Drag an image file from your desktop onto the canvas.</h4>
<canvas id="canvas" width=300 height=300></canvas>
<br>
<img width="50" src="https://cfl.dropboxstatic.com/static/images/index/rebrand/logos/glyphs/glyph_french_vanilla.svg">
</body>
</html>
Here is a set of (stripped down) tools I use to play with images
var imageTools = (function () {
var tools = {
canvas : function (width, height) { // create a blank image (canvas)
var c = document.createElement("canvas");
c.width = width;
c.height = height;
return c;
},
createImage : function (width, height) {
var image = this.canvas(width, height);
image.ctx = image.getContext("2d");
return image;
},
loadImage : function (url, callback) {
var image = new Image();
image.src = url;
image.addEventListener('load', cb);
image.addEventListener('error', cb);
return image;
},
image2Canvas : function (img) {
var image = this.canvas(img.width, img.height);
image.ctx = image.getContext("2d");
image.drawImage(ig, 0, 0);
return image;
},
getImageData : function (image) {
return (image.ctx || (this.image2Canvas(image).ctx)).getImageData(0, 0, image.width, image.height).data;
},
};
return tools;
})();
After it is parsed you will have the global variable imageTools
To load and get the image data you will have to wait for the image load callback.
var image;
var imageData;
function loaded(event){
if(event.type === "load"){
image = imageTools.image2Canvas(this);
imageData = imageTools.getImageData(image);
// image data is now in the typed array
// imageData.data
// with imageData.width and imageData.height holding the size
// there are 4 bytes per pixel in the form RGBA
}
}
imageTools.loadImage(imageURL,loaded);
To put the data back into the image after using the imageTools
// image.ctx is non standard and is a result of the imageTools adding the
// attribute ctx
image.ctx.putImageData(imageData,0,0);
To get the URL from the drop event which may be more than one image
var fileList = []; // a list of dropped images
// function called when images dropped
var imagesDropped = function(){
fileList.forEach(function(image){
// image.name is the image URL
// image.type is the mime type
});
fileList = []; // clear the file list
}
var dropEvent = function (event) {
var i,j, imagesFound;
imagesFound = false;
event.preventDefault();
dt = event.dataTransfer;
for (i = 0; i < dt.types.length; i++) { // for each dropped item
if (dt.types[i] === "Files") { // content from the file system
for (var j = 0; j < dt.files.length; j++) {
// check the mime type for the image prefix
if (dt.files[j].type.indexOf("image/") > -1){
fileList.push({ // add to image list
name : dt.files[j].name,
type : dt.files[j].type,
});
imagesFound = true; // flag images found
}
}
}
}
if(imagesFound){ // if images dropped call the handling function
imagesDropped();
}
}
Please note this is an example only and is not a cross browser solution. You will have to implement a variety of drop managers t cover all the browsers. This works on Chrome so covers the majority of users.

Phonegap camera.getPicture() missing file extension and header data

I've been struggling on this for a while.
When I upload an image in a phonegap application with camera.getPicture() and ft.upload() the image is uploaded without file extension. I read it was because of a cache thing, providing a link to the actual file entry or something.
It was annoying me but I moved on since the image was uploaded fine on my server and displayed fine too even without file extension.
But today, we figured images were sometime rotated by 90°.
I instantly made the connection between the missing part of the image data and this issue, and I guess (not sure) I am right on this point.
I read image rotated by 90° could be caused by missing header meta data, so I guess not only the file extension were missing after all..
Could someone explain me what am I missing in the code and what to do or in which direction to look ? That would be awesome.
Here is part of my code (I can give you more if needed)
navigator.camera.getPicture(function(uri) {
try {
var imageURI = uri;
...
var ft = new FileTransfer();
ft.upload(imageURI, "some_script.php", function(r) {
...
Note:The image stored in database seems fine, the issue happens when the image is displayed in an tag.
Here an example of file getting rotate once uploaded (I added manually the .jpg extension so I could upload it on noelshack otherwise not able to). As you can see, the link to image is OK but once in tag it gets rotated
http://image.noelshack.com/fichiers/2015/41/1444168922-35-1444166605.jpg
http://jsfiddle.net/c3ybkqt8/
tl;dr
How to upload an image file entirely with phonegap including file extension & metadata header and not only a sort of cached file entry.
iOS Code
function capturePhoto() {
navigator.camera.getPicture(uploadPhoto, onFail, {
quality: 50,
// allowEdit: true,
correctOrientation: true,
destinationType: Camera.DestinationType.FILE_URL,
// destinationType: Camera.DestinationType.DATA_URL
sourceType: Camera.PictureSourceType.CAMERA
}
);
}
// function onPhotoDataSuccess(imageData) {
// localStorage.setItem("ImageData",imageData);
// localStorage.setItem("captureImgFlag",captureImgFlag);
// window.location = 'profileUserImgUploadInGallary.html';
// }
function onFail(message) {
// alert('Failed because: ' + message);
}
function uploadPhoto(imageURI){
console.log(imageURI);
spinnerplugin.show();
var UserId = localStorage.getItem('UserId');
// imgPostGallary
// var img = document.getElementById('imgPostGallary');
// var imageURI = img.src;
// var imageURI = imageData;
// img.src = imageURI;
// var ImageDataUp = localStorage.getItem('ImageDataUp');
// var imageURI = ImageDataUp;
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://XYZ/uploadimg?user_id="+UserId+""), winGallary, fail, options);
console.log(ft.upload);
}
function winGallary(rGallary) {
console.log("Code = " + rGallary.responseCode);
console.log("Response = " + rGallary.response);
console.log("Sent = " + rGallary.bytesSent);
spinnerplugin.hide();
window.location = 'profileUserImgUploadInGallary.html';
}
function fail(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
Hello, here is full example it's working for me capturing photos and set in image tag and upload that photos on server. and still you have facing any problem message me.
<img id="profileImageId">
<script type="text/javascript">
var profileImage = '';
function profileCapturePhotoEdit() {
navigator.camera.getPicture(profileonPhotoDataSuccess, onFail, {
quality: 50,
// allowEdit: true,
correctOrientation: true, // using this your image not roted 90 degree
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA }
);
}
function profileonPhotoDataSuccess(imageData) {
localStorage.setItem("imageDataProfile","data:image/jpeg;base64," + imageData);
var imageDataProfile = localStorage.getItem("imageDataProfile");
document.getElementById('profileImageId').src = imageDataProfile;
}
function onFail(message) {
// alert('Failed because: ' + message);
}
</script>
<!-- uploadProfileImage -->
<button onclick="uploadProfileImage();">
Upload Profile Image
</button>
<script type="text/javascript">
function uploadProfileImage() {
var UserId = localStorage.getItem('UserId');
var img = document.getElementById('profileImageId');
var imageURI = img.src;
var options = new FileUploadOptions();
options.fileKey="file"; // your file key in your .php file change here
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg"; // your extension
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://XYZ?user_id="+UserId+""), winProfile, failProfile, options);
}
function winProfile(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// alert('Send success');
}
function failProfile(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>

How do I resize a photo into multiple photo sizes before saving in Parse.Cloud.beforeSave

First off let me start by saying I got this code working perfectly to get a thumbnail (https://parse.com/docs/cloud_modules_guide#images)
My current code is:
var Image = require("parse-image");
var photoSizesArray = {};
photoSizesArray["Thumb"] = [40,40];
photoSizesArray["Normal"] = [180,180];
Parse.Cloud.beforeSave("_User", function(request, response) {
var user = request.object;
if (!user.get("profilePicture")) {
// response.error("Users must have a profile photo.");
// return;
response.success();
return;
} else {
if (!user.dirty("profilePicture")) {
// The profile photo isn't being modified.
response.success();
return;
}
for (var key in photoSizesArray) {
Parse.Cloud.httpRequest({
url: user.get("profilePicture").url()
}).then(function(response) {
var image = new Image();
return image.setData(response.buffer);
}).then(function(image) {
// Crop the image to the smaller of width or height.
var size = Math.min(image.width(), image.height());
return image.crop({
left: (image.width() - size) / 2,
top: (image.height() - size) / 2,
width: size,
height: size
});
}).then(function(image) {
// Resize the image to 40 x 40.
return image.scale({
width: photoSizesArray[key][0],
height: photoSizesArray[key][1]
});
}).then(function(image) {
// Make sure it's a JPEG to save disk space and bandwidth.
return image.setFormat("JPEG");
}).then(function(image) {
// Get the image data in a Buffer.
return image.data();
}).then(function(buffer) {
// Save the image into a new file.
var base64 = buffer.toString("base64");
var cropped = new Parse.File("profilePicture"+key+"_" + Parse.User.current().id + ".jpg", { base64: base64 });
return cropped.save();
}).then(function(cropped) {
// Attach the image file to the original object.
user.set("profilePicture" + key, cropped);
}).then(function(result) {
response.success();
}, function(error) {
response.error(error);
});
}
}
});
My question is how do I go about saving the same photo but a different size in the same _User table?
Currently I'm getting an error that says
"Can't call multiple success/error multiple times"
or sometimes if it does work, it'll only save one of the 2 photo sizes.
Any help would be appreciated on how I should move the success/error response around.
OR if I should be looking into a different approach on how to save an additional photo size.
thanks,
So after a whole bunch research and trial and error, I finally understand how Promises work along side with httpRequests.
I initially had problems getting 2 simultaneous httpRequests going parallel to each other as for some reason, it gets overwritten or just ignored.
Here's what you need to know.
Parse.Cloud.httpRequest returns a Parse.Promise object.
this means that it has a .then and error functions (read more here: enter link description here
you actually have to RETURN the object in a for loop. This meant me placing my Parse.Cloud.httpRequest object in a separate function outside the for loop that I can call within the for loop.
When you finally have all the Promise Objects collected in a promises array, you go through it using Parse.Promise.when(promises).then()...
The following is my code that gets an uploaded photo, processes 2 sizes of it and saves them in separate _User columns - profilePictureThumb and profilePictureNormal.
var Image = require("parse-image");
Parse.Cloud.beforeSave("_User", function(request, response) {
var user = request.object;
if (!user.get("profilePicture")) {
// response.error("Users must have a profile photo.");
// return;
response.success();
return;
} else {
if (!user.dirty("profilePicture")) {
// The profile photo isn't being modified.
response.success();
return;
}
var promises = [];
var sizes = {
Normal: { width: 180, height: 180 },
Thumb: { width: 80, height: 80 }
};
for(var key in sizes) {
promises.push(
ProcessUrls(user.get("profilePicture").url(), key, sizes[key])
);
}
return Parse.Promise
.when(promises)
.then(function () {
// results are passed as function arguments
// map processed photos to result
var photos = Array.prototype.slice.call(arguments);
var result = {};
console.log("promises:" + promises)
photos.forEach(function (photo) {
console.log("photo.key: " + photo.key)
result[photo.key] = photo;
user.set('profilePicture' + photo.key, photo.file);
});
response.success();
}, function(error) {
response.error("error: " + error);
});
} // Else
});
function ProcessUrls(fullUrl, key, size) {
/* debugging
console.log("fullUrl: " + fullUrl);
console.log("key: " + key);
console.log("width: " + size["width"]);
console.log("height: " + size["height"]);
*/
return Parse.Cloud.httpRequest({ url: fullUrl })
.then(function(response) {
var image = new Image();
return image.setData(response.buffer);
})
.then(function(image) {
// Crop the image to the smaller of width or height.
var size = Math.min(image.width(), image.height());
return image.crop({
left: (image.width() - size) / 2,
top: (image.height() - size) / 2,
width: size["width"],
height: size["height"]
})
})
.then(function(image) {
// Resize the image to 40 x 40.
return image.scale({
width: size["width"],
height: size["height"]
});
})
.then(function(image) {
// Make sure it's a JPEG to save disk space and bandwidth.
return image.setFormat("JPEG");
})
.then(function(image) {
// Get the image data in a Buffer.
return image.data();
}).then(function(buffer) {
// Save the image into a new file.
var base64 = buffer.toString("base64");
var cropped = new Parse.File("profilePicture"+key+"_" + Parse.User.current().id + ".jpg", { base64: base64 });
return cropped.save()
.then(function (file) {
// this object is passed to promise below
return {
key: key,
file: file
};
})
})
};
Thanks to #Andy and a whole bunch of other StachOverflow users where I cobbled up this code together.
First of all you don't have to load source image each time. Load it once, then resize it multiple times.
You can't reuse the same Image object, so you have to create as many as you need for each individual resize operation.
Roughly the flow looks as following:
var grandPromise = Parse.Cloud.httpRequest({ url: url })
.then(function (response) {
var buffer = response.buffer;
var promises = [];
var sizes = {
normal: { width: 300, height: 300 },
thumb: { width: 100, height: 100 }
};
for(var key in sizes) {
var size = sizes[key];
var image = new Image();
// create promise for resize operation
var promise = image.setData(buffer)
.then(function(image) {
// do whatever scaling you want
return image.scale({
width: size.width,
height: size.height
});
})
.then(function (scaledImage) {
return scaledImage.data();
})
.then(function (buffer) {
var base64 = buffer.toString('base64');
var name = key + '.jpg';
var file = new Parse.File(name, { base64: base64 });
return file.save()
.then(function (file) {
// this object is passed to promise below
return {
key: key,
size: size,
file: file
};
});
});
// save promise to array
promises.push(promise);
}
// create promise that waits for all promises
return Parse.Promise
.when(promises)
.then(function ( /* result1, result2, ... */ ) {
// results are passed as function arguments
// map processed photos to result
var photos = Array.prototype.slice.call(arguments);
var result = {};
photos.forEach(function (photo) {
result[photo.key] = photo;
});
return result;
});
});
grandPromise.then(function (result) {
var normalURL = result.normal.file.url();
var thumbURL = result.thumb.file.url();
// save URLs on user model
user.set('profilePictureNormal', normalURL);
user.set('profilePictureThumb', thumbURL);
console.log('Saved normal size photo at ' + normalURL);
console.log('Saved thumb size photo at ' + thumbURL);
response.success();
}, function (err) {
console.log('Got error ' + err.code + ' : ' + err.message);
response.error(err);
});

How to upload a Cordova picture to a Laravel 4 project by using an API

I'm making a hybrid app with AngularJS and Cordova, using a Laravel 4 API & Backoffice.
I can make a picture with the application, but it does not upload. I don't really know how to upload the picture, and i don't really know how i can troubleshoot all of it.
I upload the image to the API-route i wrote, using the same upload-method as i use to do with the backoffice. This is what i have in the AngularJS-Controller, which uses Cordova to do the stuff.
var pictureSource; // picture source
var destinationType; // sets the format of returned value
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onPhotoDataSuccess(fileURI) {
var win = function (r) {
clearCache();
retries = 0;
alert('Done!');
}
var fail = function (error) {
if (retries == 0) {
retries ++
setTimeout(function() {
onPhotoDataSuccess(fileURI)
alert("kgoa ne keer opnief beginne");
}, 1000)
} else {
retries = 0;
clearCache();
alert('Ups. Something wrong happens!');
}
}
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.params = {};
params.value1 = "test";
params.value2 = "param";
// if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://10.0.1.13/ClimbrBackoffice/public/api/routes/new/create"), win, fail, options);
}
// Called when a photo is successfully retrieved
//
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 inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
$scope.capturePhoto = function(){
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 100,
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 250,
targetHeight: 400,
saveToPhotoAlbum: true,
correctOrientation: true
});
}
// A button will call this function
//
$scope.getPhoto = function(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 100,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
I searched the web for good tutorials or explanations, but they drove me crazy.
Can someone please help me out?
Thanks!
Thomas
Your Angular controller should have the following function
$scope.upload = function() {
var options = {
fileKey: "file",
fileName: "image.png",
chunkedMode: false,
mimeType: "image/png"
};
$cordovaFileTransfer.upload("http://yourdomain.com/image_handler", "/android_asset/www/img/ionic.png", options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
$scope.showAlert('Done', 'File Uploaded');
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
$scope.showAlert('Error', err);
}, function (progress) {
// constant progress updates
});}
And on your server, Laravel function could simply handle the image as:
public function getImageFromDevice(){
$destinationPath = 'uploads/';
$newImageName='MyImage.jpg';
Input::file('file')->move($destinationPath,$newImageName);
}
Do not forget to inject $cordovaFileTransfer in your controller.
That's it, this is a simple example you can extend it.
Credits to: Phonegap + Laravel 4 How to upload file

Resources