Image capture/upload with Phonegap (cordova) for iPhone not working - iphone

I have been trying to set up an app through PhoneGap (Cordova) to take images and upload them to our server. I have gone through so many of the responses on here and tried the code in them. I can get the camera up and taking a photo, I can access the phone gallery even. But I can not get it to send the image to the server. I've tried sending the image, and even sending the base64 image stream. I can't get it to the server.
Here is the javascript on the client side:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function ImageUpload() {
this.useExistingPhoto = function(e) {
this.capture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
}
this.takePhoto = function(e) {
this.capture(Camera.PictureSourceType.CAMERA);
}
this.capture = function(sourceType) {
navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFaile, {
destinationType: Camera.DestinationType.FILE_URI,
soureType: sourceType,
correctOrientation: true
});
}
this.onCaptureSuccess = function(imageURI) {
var fail, ft, options, params, win;
success = function(response) {
alert("Your photo has been uploaded!");
};
fail = function(error) {
alert("An error has occurred: Code = " + error.code + "\nMessage = "+error.message);
};
options = new FailUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
ft= new FileTransfer();
ft.upload(imageURI, 'http://style.appdev01.com/app/client-profile.php', success, faile, options);
}
this.OnCaptureFail = function(message) {
alert("Failed because: "+message);
}
};
var imageuploader = new ImageUpload();
Two buttons call imageuploader.takePhoto and .useExistingPhoto on click.
On the server side I have this php:
if(isset($_FILES['file'])) {
$target_path = "/home/style/public_html/images/client_images/app_image.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$insert = "INSERT INTO
`fut`
SET
`request` = '".serialize($_POST)."',
`file` = '".serialize($_FILES)."'";
$mysql->query($insert);
}
This is just to store the POST and FILE arrays to the db to make sure they came through and create the image.
But again, nothing is getting to the server. Any help would be GREATLY appreciated. I've tried so many versions of this code from so many questions here and all over the web.

define ('SITE_ROOT', realpath(dirname(__FILE__))); /* echo SITE_ROOT; to dir
move_uploaded_file($_FILES["file"]["tmp_name"],SITE_ROOT."/uploads/".$_FILES["file"]["name"]); // will move file, make sure uplaods has write permission!
That works for me on Android Simulator, not on Tablet, but let me know if you have it working, busy on the same thing.
$myarray = array( $_REQUEST);
foreach ($myarray as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
That you can use to check POST / GET!

Try this is my code. It has worked for me.
Encode your URL by encodeURI method
fileKey with "file" as in your server side script $_FILES['file']
uploadFile: function(refNo){
var uri = fileUpload.fileUri;
var file = uri.substr(uri.lastIndexOf('/') + 1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType="image/jpeg";
alert("name === "+uri);
options.chunkedMode = false;
var ft = new FileTransfer();
Common.ajaxLoading('show');
ft.upload(uri,encodeURI("http://172.16.1.147:80/upload/home.php") , fileUpload.uploadSuccess, fileUpload.uploadFail, options, true);
},

Related

Moodle File Manager - Crucial part

I am trying to show the file uploaded from File Manager mform element. I could store the file to mdl_files. To get the file saved is a bit hard to program. I tried implementing few options from Moodle Forums, but was stuck here. I really hope that someone can provide a solution for Moodle File manager (a crucial part). Could anyone guide me where I went wrong and suggest me to get the fileurl.
<?php
require('config.php');
require_once($CFG->libdir.'/formslib.php');
class active_form extends moodleform {
function definition() {
$mform = $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'video', get_string('video', 'moodle'), null,
$fileoptions);
$this->add_action_buttons();
}
function validation($data, $files) {
$errors = parent::validation($data, $files);
return $errors;
}
}
// Function for local_statistics plugin.
function local_statistics_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload,
array $options=array()) {
global $DB;
if ($context->contextlevel != CONTEXT_SYSTEM) {
return false;
}
$itemid = (int)array_shift($args);
if ($itemid != 0) {
return false;
}
$fs = get_file_storage();
$filename = array_pop($args);
if (empty($args)) {
$filepath = '/';
} else {
$filepath = '/'.implode('/', $args).'/';
}
$file = $fs->get_file($context->id, 'local_statistics', $filearea, $itemid, $filepath,$filename);
if (!$file) {
return false;
}
// finally send the file
send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
}
// Form Settings
$fileoptions = array('maxbytes' => 0, 'maxfiles' => 1, 'subdirs' => 0, 'context' =>
context_system::instance());
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'video', $fileoptions, context_system::instance(),
'local_statistics', 'video', 0);
$mform = new active_form(null, array('fileoptions' => $fileoptions));
// Form Submission
if ($data = $mform->get_data()) {
$data = file_postupdate_standard_filemanager($data, 'video', $fileoptions,
context_system::instance(), 'local_statistics', 'video', 0);
$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'local_statistics', 'video', '0', 'sortorder', false);
foreach ($files as $file) {
$fileurl = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(),
$file->get_filearea(), $file->get_itemid(), $file->get_filepath(),
$file->get_filename());
echo $fileurl;
}
}
?>
I've had a quick look through your code and it all looks reasonable, but you've not included the code of the local_statistics_pluginfile() function in local/statistics/lib.php - without that function, Moodle is unable to authenticate any requests from the browser to serve files, so all files will return a 'file not found' message.
Have a look at the documentation for details of what the x_pluginfile function should look like (or look for examples in any of the core plugins in Moodle): https://docs.moodle.org/dev/File_API#Serving_files_to_users

How to save multiple image path to database while image is saved to server

I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}

How to migrate mysqli to pdo

Hi I was wondering how I would migrate a mysqli php file to use PDO. Would anyone be able to take a look at my code and see if I'm on the right track?
This is my original (mysqli) code:
<?php
// connecting to database
$conn = new mysqli('xxxxxx', 'xxxxxx', 'password', 'xxxxxx');
$match_email = 'email';
$match_passhash = 'passhash';
if (isset($_POST['email'])) {
$clean_email = mysqli_real_escape_string($conn, $_POST['email']);
$match_email = $clean_email;
}
if (isset($_POST['passhash'])) {
$clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
$match_passhash = sha1($clean_passhash);
}
$userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
WHERE email = '$match_email' AND passhash = '$match_passhash'
AND userlevel='user' AND confirmed='true' AND blocked='false';";
$userresult = $conn->query($userquery);
if ($userresult->num_rows == 1) {
$_SESSION['authorisation'] = 'knownuser';
header("Location: userhome.php");
exit;
} else {
$_SESSION['authorisation'] = 'unknownuser';
header("Location: userlogin.php");
exit;
}
?>
And this is my attempt to migrate it to PDO:
<?php
// connecting to database
$dbh = new PDO("mysql:host=xxxxxx; dbname=xxxxxx", "xxxxxx", "password");
$match_email = 'email';
$match_passhash = 'passhash';
if (isset($_POST['email'])) {
$clean_email = mysqli_real_escape_string($conn, $_POST['email']);
$match_email = $clean_email;
}
if (isset($_POST['passhash'])) {
$clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
$match_passhash = sha1($clean_passhash);
}
$userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
WHERE email = ':match_email' AND passhash = ':match_passhash' AND
userlevel='user' AND confirmed='true' AND blocked='false';";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":match_email", $match_email);
$stmt->bindParam(":match_passhash", $match_passhash);
$stmt->execute();
$userresult = $conn->query($userquery);
if ($userresult->num_rows == 1) {
$_SESSION['authorisation'] = 'knownuser';
header("Location: userhome.php");
exit;
} else {
$_SESSION['authorisation'] = 'unknownuser';
header("Location: userlogin.php");
exit;
}
?>
I'm also not sure how to count the number of rows returned in PDO.
If anyone would be able to help me out that wold be very great.
A million thanks in advance!
When using prepared statements and $stmt->bindValue() or $stmt->bindParam() you do not need to escape values with mysqli_real_escape_string(), PDO will do that for you.
Just remember to set a correct data type for the value. That is the third argument in the bind functions and it is a string by default so your code here is fine. I would only use bindValue() instead of bindParam() as you do not need references.
$stmt->execute() will run your prepared statement as a query. The other $conn->query() does not work with prepared statements. It is for raw queries, like you used to have with MySQLi.
When $stmt->execute() runs your response is saved in the $stmt object. For row count use $stmt->rowCount().

How to get the facebook app_access_token?

I want to create a score for my Facebook app and I know you need an app_access_token for that. Some posts say, the only way to get an app_access_token is via PHP, like this:
<?php
$APPLICATION_ID = YOUR_APP_ID;
$APPLICATION_SECRET = YOUR_APP_SECRET;
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $APPLICATION_ID .
"&client_secret=" . $APPLICATION_SECRET .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
?>
Is the token you get via this PHP script different from the so called "app token" you find on
https://developers.facebook.com/tools/access_token/?
(looks like this: APPLICATION_ID|lvATVyhp1m.............w)
and is acually the same you get by calling
https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=client_credentials directly.
So why must this call be made via PHP?
You can get token by various ways
<a href='https://www.facebook.com/dialog/oauth?client_id=2926561407xxxxx&redirect_uri=http://localhost:8080/fb/getCode.html&rcount=1&scope=email,read_stream'>Login</a>
It will return the token through URL you can get it by:
function getURLParameters(access_token)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == "code")
{
code = arrParamValues[i];
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
getURLParameters();

Uploadify stuck at 100% but still does the upload

I seem to have a problem with uploadify. It always get stuck at 100% on the first file, no matter what the file is. I am using Zend on my Wamp and it works fine there but as soon as I upload it on my linux server it gets stuck. The file is uploaded and renamed but it never fires the onComplete event and stays at 100% on the first file.
Here is my javascript:
$('#fileInput').uploadify({
'uploader' : 'http://test.thevenuelist.co.uk/js/uploadify/uploadify.swf',
'script' : 'http://test.thevenuelist.co.uk/ajax/uploadify',
'cancelImg' : 'http://test.thevenuelist.co.uk/js/uploadify/cancel.png',
'folder' : '/userdata/images/',
'auto' : true,
'multi' : true,
'fileDesc' : 'Image Files (*.jpg;*.jpeg;*.gif;*.png)',
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'buttonText' : 'Upload Images',
'removeCompleted' : true,
'onComplete' : function (event, queueID, fileObj, response, data) {
var answer = eval('(' + response + ')');
if(answer.result == "success")
{
$("#hdnImages").val($("#hdnImages").val() + answer.fileName + ",");
var toAdd = "<li><img src='/images/delete.png' id='removeItem' rel='"+answer.fileName+"' style='cursor:pointer;' title='Remove' alt='Remove'/> Image "+answer.realName+" uploaded</li>";
$("#completedItemsList").append(toAdd);
}
},
'onError': function (event, queueID ,fileObj, errorObj) {
alert(errorObj.info);
}
});
And here is my Zend code behind:
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT']. '/' . $_REQUEST['folder'] . '/';
$fileNameArray = explode('.',$_FILES['Filedata']['name']);
$hash = substr(md5(microtime()),0,5);
$finalFileName = $fileNameArray[0].$hash.'.'.$fileNameArray[1];
$targetFile = str_replace('//','/',$targetPath) . $finalFileName;
if(move_uploaded_file($tempFile,$targetFile))
{
$data = array("result"=>"success","fileName"=>$finalFileName,"realName"=>$_FILES['Filedata']['name']);
}
else
{
$data = array("result"=>"failed");
}
echo Zend_Json::encode($data);
Any help would be greatly appreciated. I have spent way too much time trying to figure it out. I need my onComplete event to work so I can finish my forms.
I found with uploadify I had to return either a 1 or a 0 for success or failure to get it to work.