Pass image through ajax using cordova - ajax

I am developing my mobile application using ionic framework and I want it to connect to my API through ajax. Currenty, in the mobile side, which is I am using Ionic Framework, I want to upload an image and pass it to my api through ajax. I am using Cordova for the upload but it seems it doesn't found the URL I indicated.
Here's the HTML
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button>
</div>
</ion-footer-bar>
Here's the uploadImage() function in the controller (Just copied the code in a site. Forgot where) EDIT: added targetPath
$scope.uploadImage = function() {
// Destination URL
var url = "http://192.168.0.19/identificare_api/public/api/plants/image";
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
var jsonparse = JSON.parse(result);
$scope.showAlert(jsonparse);
}
But in the upload part, I want to do it in ajax to indicate the method for the URL but the problem I don't know what put in data.
$.ajax({
url: "http://192.168.0.19/identificare_api/public/api/plants/image",
type: 'POST',
data:
success:function(json){
var jsonparse = JSON.parse(json);
alert(jsonparse);
},
error:function(){
alert("Error");
}
});
Can someone help me with this issue?
UPDATE: Applied here #Blauharley's comment below
I had another issue here. I returned the $_FILES['image']['tmp_name'] in the API side but it returns nothing but when I returned the $_FILES['image']['name'], it returned my_image.jpg. Why it doesn't have tmp_name?
$scope.uploadImage = function() {
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
$scope.getBase64ImageByURL(targetPath).then(function(base64Image){
var blob = $scope.base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('image', blob, "my_image.jpg");
fd.append('user_token', "rLUrh37rfTozuBxmemHtlKMgH");
$.ajax({
url: 'http://192.168.0.19/identificare_api/public/api/plants/image',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success:function(res){
alert(res);
},
error:function(err){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
};
$scope.getBase64ImageByURL = function(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
};
$scope.base64ToBlob = function(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
};
ADDED: API side
public function image(){
echo json_encode($_FILES['image']['tmp_name']);
}

Related

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

error in image while uploading through ajax

I am trying to upload image through ajax. at theclient side i am using this code.
$(document).on('change','.image_upload',function(){
readURL(this);
});
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = encodeURIComponent(image_data);
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
while at the client side i am using codeigniter to save this as image. Image file is created but it won't display because it contains errors.Here is my CI function where this ajax request is being sent.
public function new_valet_picture(){
$user = $this->session->user_id;
$image_data = $this->input->post('valet_image');
$name= "valet_".$user.time().".png";
$profile_image = str_replace('data:image/png;base64,', '', $image_data);
$profile_image = str_replace(' ', '+',$profile_image);
$unencodedData=base64_decode($profile_image);
$pth = './uploads/valet_images/'.$name;
file_put_contents($pth, $unencodedData);
echo $name;
}
can anybody figure out where i am wrong.
you just wrong to pass parameter in ajax request :
this is your code
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
data:'valet_image='+image_code, is wrong pass and change that to data : {vallet_image : image_code}.
just changing the position of encodeURIComponent() helped me
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(encodeURIComponent(e.target.result));
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = image_data;
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}

I can not return an image file and show it in View using Ajax in Asp.net MVC

$.ajax({
type: 'GET',
dataType: 'image/jpeg',
url: '/Home/GetImage/' + img ,
success: function (data) {
i = new Image();
i.src = data;
$('#imageresult').append(i);
},
error: function () {
alert('error');
},
});
[HttpGet]
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);
return File(stream.ToArray(), "image/jpeg");
}
It always falls into error function. If i remove dataType, then it doesn't fall into error function but it just shows long strings in the view. Why doesn't that work and show image in view?
You can do something Like this:
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);
return Json(Convert.ToBase64String(stream.ToArray()), JsonRequestBehavior.AllowGet);
}
and the Ajax call:
$.ajax({
type: 'GET',
url: '#Url.Action("GetImage", "Home")',
success: function (data) {
$("#ItemPreview").attr('src', 'data:image/png;base64,' + data);
},
error: function () {
alert('error');
},
});
and the view:
<img id="ItemPreview" src="" />
of course you can append img dynamically, then bind its source after.
You are confusing the URL of an image with its actual content (the graphic bytes).
The /GetImage call returns the bytes, but you can never put data bytes in the i.src attribute because that attribute needs to be fed a URL.
It might work if you forget about the Ajax call and just use i.src = '/Home/GetImage/' + img;.

Firefox convertImgToDataURLviaCanvas is not working on Firefox but working in chrome and IE

My following function is not working in firefox but works in chrome
function convertImgToDataURLviaCanvas(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
I have to pass the base64 encoded to a webservice, the encoded string which I am getting in firefox is failing at webservice end, but the one I am getting in chrome and IE is working. Following is the code which gets called on Imageupload
$("#avatar1").on('change',function(event){
var selectedFile = this.files[0];
var tmppath = URL.createObjectURL(event.target.files[0]);
// $('.profile-image').append('<img src="'+tmppath+'" />');
var convertFunction = convertImgToDataURLviaCanvas;
convertFunction(tmppath, function(base64Img){
console.log(base64Img);
var imagebase64Obj = new Object();
imagebase64Obj.data = base64Img;
$.ajax({
url : "/bin/mercer/saml/myProfileController?q=updateavatar",
type : "POST",
data : imagebase64Obj,
success : function(data, textStatus, jqXHR) {
// data - response from server
window.location.reload();
alert("success");
},
error : function(jqXHR, textStatus,
errorThrown) {
alert("error");
}
});
});
});
Please help me get what is going wrong, or some other variant function which works in firefox

how to extract URL parameter from POST request in nodejs and expressjs

REQUEST URL http://localhost:9090/rest-api/fetchDetailedProductInfo?prodId=1&tempId=123
fetchDetailedProductInfo: function (prodId) {
var self = this;
var URL = 'http://localhost:9090/rest-api/fetchDetailedProductInfo'
$.ajax({
url: URL,
dataType: 'json',
contentType:'json',
type:'GET',
data: {
'prodId':prodId,
'tempId':123
},
success:function(responce) {
self.renderUI(responce.json);
},
error: function (err) {
console.log('ERROR',err)
}
});
},
# SERVER SIDE
router.get('/rest-api/fetchDetailedProductInfo', function (req, res) {
var prodId = req.param('prodId');
var tempId = req.param('tempId');
res.send(prodId + '----' + tempId);
}
I think you confused with req.params and req.query. Here is link to another question
Use req.query
var prodId = req.query.prodId;
var tempId = req.query.tempId;
Please see this

Resources