titanium:image upload to server issue - titanium-mobile

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"]);

Related

ionic how to log http response in 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();
});
};
})

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.

file download with XMLHttpRequest

I am having a hard time implementing a simple file download script.
This is what I have so far, working ok :
Open an XMLHttpRequest
Get remote file as blob binary
Show download progress
My problem is :
creating a custom download directory
renaming downloaded file as original source name
downloaded file does not include its extension
Possibility to add the option to prompt a save as location before download ?
This is the snippet :
$('#DownloadBtn').click(function(e) {
e.preventDefault();
var urlFile = $(this).attr('href'); // remote file www.blabla.com/soft123.bin
var fileName = ''; // Get remote file name & extension ?
var progressBar = document.querySelector('progress');
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
function onError(e) {
console.log('Error', e);
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.open('GET', urlFile, true);
xhr.responseType = 'blob';
var resourceDIRLOC = "Downloads";
xhr.onload = function(e) {
window.requestFileSystem(TEMPORARY, 10 * 1024 * 1024, function(fs) {
fs.root.getDirectory(fs.root.fullPath + '/' + resourceDIRLOC, {
create: true
}, function(dir) {
resourceDIR = dir;
fs.root.getFile(fileName, {
create: true
}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) {};
writer.onerror = function(e) {};
var blob = new Blob([xhr.response], {
type: ' application/octet-stream'
});
writer.write(blob);
}, onError);
}, onError);
}, onError);
}, onError);
};
function updateProgress(e) {
if (e.lengthComputable) {
$(progressBar).show();
var i = (e.loaded / e.total) * 100;
progressBar.value = i;
if (i == 100) {
$(progressBar).hide();
}
}
}
xhr.send();
});
The downloaded file is located under FileSystem->000->t with 00 as name ( not soft123.bin )
I am not sure if it is possible to give the user an option to choose a download directory outside FileSystem? As defined above, target directory resourceDIRLOC = "Downloads" but the request is not creating this folder ? neither giving the file a name and extension
Any advise is appreciated
Thanks
Here is how you can keep track download progress and choose download directory in with Node-Webki. I was at first trying to download using an XMLHttpRequest in order to monitor download progress but I was having difficulties with the FileSystem API. This did the job just as I wanted, a simple file download with a progress bar. Hope it is helpful.
function download(file_url) {
var fs = require('fs');
var url = require('url');
var http = require('http');
var options = {
host: url.parse(file_url).host,
port: 80,
path: url.parse(file_url).pathname
};
var file_name = url.parse(file_url).pathname.split('/').pop();
var file = fs.createWriteStream('./' + file_name);
http.get(options, function(res) {
var fsize = res.headers['content-length'];
res.on('data', function(data) {
file.write(data);
progress(100 - (((fsize - file.bytesWritten) / fsize) * 100), $('#progressBar'));
}).on('end', function() {
file.end();
});
});
}
function progress(percent, $element) {
console.log("Download: " + parseInt(percent) + " %")
var progressBarWidth = percent * $element.width() / 100;
$element.find('div').css("width", progressBarWidth);
}
Answer found here

How to check file size when uploading photo using ajaxupload3.5

I'm using ajaxuploader to upload and change user photo using the solution from here:http://www.c-sharpcorner.com/blogs/4183/upload-image-by-ajax-uploader-with-jquery.aspx
The code below works fine but I don't know how to check file size in client side or (if it's not possible in client side) how to get the response from server side. In mycode below the response id the HTML of the whole page.
<script src="../js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
<script src="../js/ajaxupload.3.5.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('#<%=status_message.ClientID%>').html('');
var btnUpload = $('#upload_button');
var status = $('#status_message');
new AjaxUpload(btnUpload, {
action: 'test_photoUpload.aspx/uploadPhoto',
name: 'uploadfile',
onSubmit: function (file, ext) {
$('#<%=status_message.ClientID%>').html('');
$('#imgLoad').show();
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
// extension is not allowed
$('#imgLoad').hide();
$('#<%=status_message.ClientID%>').html('Only JPG, PNG or GIF files are allowed');
alert("submitted");
return false;
}
// if (file.ContentLength > 1024 * 1024 * 2) {
// $('#<%=status_message.ClientID%>').html('Please upload photo less than 2MB size.');
// alert("submitted");
// return false;
// }
},
onComplete: function (file, response) {
alert(response);
status.text('');
$('#<%=hdPhoto.ClientID%>').val(file);
$('#<%=imgPhoto.ClientID%>').attr('src', 'UserImages/' + file);
// $('#<%=status_message.ClientID%>').html(file.toString());
$('#imgLoad').hide();
return false;
}
});
});
</script>
private string uploadPhoto()
{
string chkResult = "false";
//upload photo code
string i = Request.Files.ToString();
string ext = Path.GetExtension(Request.Files[0].FileName.ToString().ToLower());
if (ext == ".png" || ext == ".jpg" || ext == ".gif" || ext == ".jpeg")
{
if (Request.Files[0].ContentLength <= 1024 * 1024 * 2)
{
if (File.Exists(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName)))
File.Delete(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));
Request.Files[0].SaveAs(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));
chkResult = "true";
}
else
{
status_message.InnerHtml = "Please upload less than 2MB size.";
chkResult = "false";
}
}
else
{
status_message.InnerHtml = "Please upload only png, jpg, jpeg or gif file.";
chkResult = "false";
}
// Response.Close();
// Response.End();
return chkResult;
}
I've tried to serialize the response to Json and return but the response is the same HTML converted to string. I tried like this:
$(function () {
$('#<%=status_message.ClientID%>').html('');
var btnUpload = $('#upload_button');
var status = $('#status_message');
new AjaxUpload(btnUpload, {
action: 'test_photoUpload.aspx/uploadPhoto',
name: 'uploadfile',
dataType: 'json',
contentType: "application/json; charset=utf-8",
onSubmit: function (file, ext) {
$('#<%=status_message.ClientID%>').html('');
$('#imgLoad').show();
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
// extension is not allowed
$('#imgLoad').hide();
$('#<%=status_message.ClientID%>').html('Only JPG, PNG or GIF files are allowed');
alert("submitted");
return false;
}
// if (file.ContentLength > 1024 * 1024 * 2) {
// $('#<%=status_message.ClientID%>').html('Please upload photo less than 2MB size.');
// alert("submitted");
// return false;
// }
},
onComplete: function (file, response) {
var obj = JSON.stringify(response);
//var obj = jQuery.parseJSON(response);
alert(obj);
alert(response);
status.text('');
$('#<%=hdPhoto.ClientID%>').val(file);
$('#<%=imgPhoto.ClientID%>').attr('src', 'UserImages/' + file);
// $('#<%=status_message.ClientID%>').html(file.toString());
$('#imgLoad').hide();
return false;
}
});
});
using System.Web.Script.Serialization;
using System.Web.Script.Services;
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
private string uploadPhoto()
{
string chkResult = "false";
//upload photo code
string i = Request.Files.ToString();
string ext = Path.GetExtension(Request.Files[0].FileName.ToString().ToLower());
if (ext == ".png" || ext == ".jpg" || ext == ".gif" || ext == ".jpeg")
{
if (Request.Files[0].ContentLength <= 1024 * 1024 * 2)
{
if (File.Exists(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName)))
File.Delete(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));
Request.Files[0].SaveAs(Server.MapPath("UserImages") + "\\" + System.IO.Path.GetFileName(Request.Files[0].FileName));
chkResult = "true";
}
else
{
status_message.InnerHtml = "Please upload less than 2MB size.";
chkResult = "false";
}
}
else
{
status_message.InnerHtml = "Please upload only png, jpg, jpeg or gif file.";
chkResult = "false";
}
// Response.Close();
// Response.End();
//return chkResult;
var keyValues = new Dictionary<string, string>
{
{ "success", "success" },
{ "error", "error" }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
//Response.Write(json);
return json;
}
I've also tried to use webmethod and static uploadPhoto method but the response is the same.
Any help is appreciated.
It works for me. I instantiate the AjaxUpload in a variable, then I use the variable itself to call an outside script, which submits the file. After that, I get the input information from inside the AjaxUpload script.
var btnUpload = $("#upload");
up_archive = new AjaxUpload(btnUpload, {
action: 'FileUpload.php',
name: 'upload_archive',
responseType: 'json', //get the server response as JSON
autoSubmit: false, //I'll set some informations about the archive outside this script
onChange: function(file, ext){
//check the file size
if (up_archive._input.files[0].size > 2097152){ //2MB
//show alert message
alert('Selected file is bigger than 2MB.');
return;
}
},
onSubmit: function(file, ext){
desc_archive = $("#desc_archive").val();
this.setData( {desc_archive: desc_archive} ); //set a description for the archive to be uploaded
},
onComplete: function(file, response){
$("#desc_archive").val('');
$("#div_response").html(response.message);
}
});

Resources