I am trying to post an image (as part of a form) to a PHP server from a Worklight V6 app using the HTTP adapter. The image is base64 encoded
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 8,
destinationType: navigator.camera.DestinationType.DATA_URL });
.. later in the code
$('#myImageImg').attr('src', "data:image/jpeg;base64," + imageData);
I send the image to the adapter
var img = $('#myImageImg').attr('src');
var formData = {"someField" : name,
"image" : img };
var invocationData = {
adapter : 'emailAdapter',
procedure : 'sendEmail',
parameters : [ formData ]
};
var options = {
onSuccess : sendEmailOK,
onFailure : sendEmailFail,
invocationContext : {}
};
$.mobile.showPageLoadingMsg();
WL.Client.invokeProcedure(invocationData,options);
In my HTTP adapter I uriencode the form data and send it x-www-form-urlencoded
function sendEmail(inputData) {
var uri = 'myStuff/sendEmail.php';
var imageData="image='" + inputData.image+"'";
var formData = encodeURI(imageData);
var input = {
method : 'post',
returnedContentType : 'html',
path : path,
body: { "contentType" : "application/x-www-form-urlencoded",
'content' : formData
}
When I decode the data and save it to a file using my php server, the Windows photo viewer displays an error message " Windows photo viewer can't open this picture because the file appears to be damaged, corrupted or is too large".
I am a php beginner, but here is the php code that I used
<?php
$image = $_POST['image']
$decoded=base64_decode($image);
file_put_contents('C:\apache\htdocs\myStuff\newImage.JPG',$decoded);
I'm sure I'm making some sort of silly beginner mistake, but I'm not sure if it's in my adapter code, the php code or in my worklight client code. Thank you in advance for any suggestions.
JT
David D saved me. In the adapter code, I had
To get the code to work we changed it to
var input = { method : 'post', returnedContentType : 'html', path : path,
body: { "contentType" : "application/x-www-form-urlencoded",
The thought here is that base64 encoded strings can have 1 or 2 trailing ='s to pad out to an even number. encodeURI doesn't encode ='s so those were getting lost in translation from the adapter to my PHP server.
Also as Dave wrote above, I needed to strip out the "data:image/jpeg;base64," at the front of the base64 encoded data. Thanks David!!!
I think the problem is "data:image/jpeg;base64," at the front of the base64 encoded data. Either send the image to the adapter w/o that prefix, or strip it off in the adapter before posting to the service.