ionic how to log http response in xcode - xcode

I am trying to upload an image to cloudinary using ionic cordova plugin. I can successfully post my image to cloudinary, but the response i received in xcode shows [object Object]. I would like to get the details of the response.
I tried printing the result using different ways such as iterating the keys of object, and nothing is been printed. is there a way for xcode to print out ionic console.log response? My code is as follow:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $cordovaCamera, $cordovaGeolocation, $cordovaFileTransfer, $q, $base64, $translate) {
//$scope.$inject = ['$cordovaCamera','$cordovaGeolocation','$cordovaFileTransfer'];
$scope.imageURI = '';
$scope.log=function(){
console.log('hello~~~');
};
$scope.takePicture = function() {
console.log('taking pictures ....');
var uploadOptions = {
params : { 'upload_preset': "MY_PRESET"}
};
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
};
$cordovaCamera.getPicture(options).then(function(imageData) {
$scope.imageURI = imageData;
var ft = new FileTransfer();
function win (){
console.log('upload successful');
}
function fail(){
console.log('upload fail');
}
return $cordovaFileTransfer.upload("https://api.cloudinary.com/v1_1/MY_DOMAIN/image/upload", $scope.imageURI, uploadOptions);
})
.then(function(result){
console.log('result is~~~~~~ ', result);
console.log('print the result object '); // this shows nothing
var test1=JSON.parse(decodeURIComponent(result.response);
var test2=JSON.parse(decodeURIComponent(result);
console.log('test1 is ', test1); // didn't even print!!
console.log('test2 is ', test2); // didn't even print!!
for(var property in result[0]) {
console.log(property + "=" + obj[property]); // nothing here
}
for(var property in result[1]) {
console.log(property + "=" + obj[property]);// nothing here
}
for(var property in result) {
console.log(property + "=" + obj[property]);// nothing here
}
var url = result.secure_url || '';
var urlSmall;
if(result && result.eager[0]) { // this is not working
urlSmall = result.eager[0].secure_url || '';
console.log('url ~~~~~~~~ is ', urlSmall);
chat.sendMessage(roomId,'', 'default', urlSmall, function(result){
console.log('url is ', urlSmall);
console.log('message image url successfully updated to firebase');
})
}
// Do something with the results here.
$cordovaCamera.cleanup();
}, function(err){
// Do something with the error here
console.log('something is erroring')
$cordovaCamera.cleanup();
});
};
})

Related

Ionic 2: calling function after xhr.onload

In ionic 2, I'm using below code to upload the file(.pdf and .doc extension) into server via API. But I'm not able to call any function after resp.success == 1 or not able to use any global variables.I'm getting error like property doesn't exist on type xmlhttpeventtarget As I want to navigate user to next page on successful submission of the file I need call some function inside success.
xhr.open('POST', "myurl", true);
xhr.onload = function() {
if (xhr.status == 200) {
var resp = JSON.parse(xhr.response);
console.log('Server got: in IOS ', resp);
console.log('Server got: in IOS ', resp.message);
if(resp.success == 1)
{
console.log("THIS IS SUCCESS")
}
else{
alert(resp.message)
return
}
};
}
xhr.send(this.fd);
A better way to solve this would be by using arrow functions like this:
xhr.open('POST', "myurl", true);
xhr.onload = () => {
if (xhr.status == 200) {
var resp = JSON.parse(xhr.response);
console.log('Server got: in IOS ', resp);
console.log('Server got: in IOS ', resp.message);
if(resp.success == 1) {
console.log("THIS IS SUCCESS");
// Now 'this' points to the component :) !!
this.yourcustomfunction();
this.yourvariableblename;
} else{
alert(resp.message)
return
}
};
}
xhr.send(this.fd);
Notice that now we do
xhr.onload = () => {...});
instead of
xhr.onload = function() {...});
By using arrow functions, the this property is not overwritten and still references the component instance (otherwise, the this keyword points to the inner function, and your custom method and variable are not defined in it).
Hi I found solution to this problem.By creating a variable which has this reference, the snippet is as below.
var self = this;
xhr.open('POST', "myurl", true);
xhr.onload = function() {
if (xhr.status == 200) {
var resp = JSON.parse(xhr.response);
console.log('Server got: in IOS ', resp);
console.log('Server got: in IOS ', resp.message);
if(resp.success == 1)
{
console.log("THIS IS SUCCESS")
self.yourcustomfunction()
self.yourvariableblename
}
else{
alert(resp.message)
return
}
};
}
xhr.send(this.fd);

Sending Data to a Server using JavaScript (Firefox Addon)

I would like to send some data to an external server within an Firefox extension.
I tried this code snippet but it doesn’t work, due to Same-Origin-Policy.
$.ajax({
type: "POST",
url: 'https://127.0.0.1:54321',
data: ({foo: "bar"}),
crossDomain: true,
dataType: 'json'
}).done(function () {
alert("done");
}).fail(function(xhr, status, error) {
// var err = eval("(" + xhr.responseText + ")");
alert((xhr.responseText));
});
Since this does not work, I tried this tutorial:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
That got me this piece of code:
var invocation = new XMLHttpRequest(); var url = 'https://127.0.0.1:54321';
invocation.open('POST', url, true);
invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
invocation.setRequestHeader('Content-Type', 'application/xml');
invocation.onreadystatechange = handler;
invocation.send(document.body);
This code also doesn't work and Firefox prompts that I should use CORS.
The weird thing is that it works if I don't use HTTPS (on non-HTTPS sites).
Note: On https://127.0.0.1:54321 runs a Java SSLServerSocket.
Copy paste this:
var {Cu, Cc, Ci} = require('chrome'); //addon-sdk way
//var {Cu: utils, Cc: classes, Ci: instances} = Components; //non addon-sdk
Cu.import('resource://gre/modules/Services.jsm');
function xhr(url, cb) {
let xhr = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
let handler = ev => {
evf(m => xhr.removeEventListener(m, handler, !1));
switch (ev.type) {
case 'load':
if (xhr.status == 200) {
cb(xhr.response);
break;
}
default:
Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']');
break;
}
};
let evf = f => ['load', 'error', 'abort'].forEach(f);
evf(m => xhr.addEventListener(m, handler, false));
xhr.mozBackgroundRequest = true;
xhr.open('GET', url, true);
xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING;
//xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something
xhr.send(null);
}
xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1', data => {
Services.prompt.alert(null, 'XHR Success', data);
var file = OS.Path.join(OS.Constants.Path.desktopDir, "test.png");
var promised = OS.File.writeAtomic(file, data);
promised.then(
function() {
alert('succesfully saved image to desktop')
},
function(ex) {
alert('FAILED in saving image to desktop')
}
);
});

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

Angularjs upload service with onLoad image?

i have some issues with onload image and angular-fie-upload. first, i have to validate an image size after that i will upload this image to server side with the following code. my service look like that :
Services.factory('$uploadWrapper', ['$upload' , '$logger' , function ($upload, $logger) {
return function (url, file, informations, onSuccess, onError, onProgress) {
url = url || angular.noop;
file = file || angular.noop;
informations = informations || angular.noop;
onSuccess = onSuccess || angular.noop;
onError = onError || angular.noop;
onProgress = onProgress || angular.noop;
$upload.upload({
url: url,
method: 'POST',
// headers: {'header-key': 'header-value'},
// withCredentials: true,
data: informations,
file: file // or list of files: $files for html5 only
/* set the file formData name ('Content-Desposition'). Default is 'file' */
//fileFormDataName: myFile, //or a list of names for multiple files (html5).
/* customize how data is added to formData. See #40#issuecomment-28612000 for sample code */
//formDataAppender: function(formData, key, val){}
}).progress(function (evt) {
$logger.info(Math.min(100, parseInt(100.0 * evt.loaded / evt.total)));
onProgress(evt);
}).success(function (response) {
$logger.info('POST' + url + angular.toJson(response))
onSuccess(response);
}).error(function (error) {
$logger.error('POST' + url + ' ' + angular.toJson(error));
onError(error);
});
}
}]);
and for validation process, i will create an image to take the width and the height of my image :
$scope.onFileSelect = function ($files) {
$scope.loading = true;
//$files: an array of files selected, each file has name, size, and type.
file = $files[0];
var img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = function () {
console.log(this.width + "x" + this.height);
if (img.width > sizes.width && img.height > sizes.height) {
$uploadWrapper(pinholeAdminServerRoutes.image.upload, file, {
"operationType": 'channels',
"objectId": $scope.channel.id,
"size": 'large'
}, function (response) {
$scope.loading = false;
}, function (error) {
$scope.errors.push(error);
$scope.loading = false;
});
} else {
$scope.imageSizeNotValid = true;
$scope.loading = false;
}
console.log('finish loading');
};
};
but, my service won't work inside the onload block. but the same service will work without the onload block.
i finally got a solution by using $scope.$apply inside the onload event.

titanium:image upload to server issue

Hello friends,
I am developing app in Titanium and also develop a functionality to upload image to server using POST method and I am select a photo from photo gallery and send to the server but I am can't got successfully response from server and also I want to send image name as a parameter like 45645.png and media parameters etc but I can't send image name so please give me idea how can i solve my issue.
Refer upload image to server: http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-build-an-image-uploader/
//photo gallery for select photo
function getPhotGallery ()
{
Titanium.Media.openPhotoGallery({
success:function(event)
{
//var cropRect = event.cropRect;
var image = event.media;
// set image view
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
uploadPhotoImageView.image = image;
UploadPhotoToServer(uploadPhotoImageView.image);
}
else
{
}
//Titanium.API.info('PHOTO GALLERY SUCCESS cropRect.x ' + cropRect.x + ' cropRect.y ' + cropRect.y + ' cropRect.height ' + cropRect.height + ' cropRect.width ' + cropRect.width);
},
cancel:function()
{
},
error:function(error)
{
},
allowEditing:true,
//popoverView:popoverView,
//arrowDirection:arrowDirection,
mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
});
}
//upload photo to server uisng POST method
function UploadPhotoToServer(media)
{
//var filename = mobileNumber.value + '.png';
var filename = '123456.png';
if (Titanium.Network.online == true)
{
var imgUploadLoader = Titanium.Network.createHTTPClient();
//open the client
imgUploadLoader.open('POST', 'http://projects.spinxweb.net/ContactsTracking/iphone-file-upload.aspx');
// send the data
imgUploadLoader.send(
{
media: media,
"name": filename
});
imgUploadLoader.onerror = function(e)
{
Ti.API.info('IN ERROR ' + e.error);
alert('Sorry, we could not upload your photo! Please try again.');
};
imgUploadLoader.onload = function()
{
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
if(this.responseText != 'false')
{
var url = this.responseText; //set our url variable to the response
Ti.API.log('Upload image url:'+url);
//alert('Upload photo successfully');
//getLoginData();
}
else
{
alert('Whoops, something failed in your upload script.');
}
};
imgUploadLoader.onsendstream = function(e)
{
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
if(Ti.Platform.osname == 'android')
{
}
else
{
}
};
}
else
{
alert('You must have a valid Internet connection in order to upload this photo.');
}
}
Not sure if this is exactly what you're looking for, but I've had success with this code:
eventSuccess : function ( e )
{
var xhr = Ti.Network.createHTTPClient ( );
xhr.open ( "POST", 'yourserver.com/webservice.php' );
xhr.setTimeout ( 20000 );
xhr.send (
{
"CommandType" : "image",
"file" : e.media,
"name" : filename
});
xhr.onload = function ( e )
{
Ti.API.info ("image sent to server");
}
}
This is running when a success event is coming back from the camera. The image is then sent to the server.
You'll then need something on the server side, like this:
move_uploaded_file ($_FILES["file"]["tmp_name"], "incoming/images/" . $_FILES["file"]["name"]);

Resources