How save image in parse cloud using javascript - javascript

we are trying to save image in Parse using CloudCode.
we followed this link.
we are new to javascript,plz guide us...!
Thanks in advance.......
var url = file.url();
Parse.Cloud.httpRequest({ url: url }).then(function(response) {
// Create an Image from the data.
var image = new Image();
return image.setData(response.buffer);
}.then(function(image) {
// Scale the image to a certain size.
return image.scale({ width: 64, height: 64 });
}.then(function(image) {
// Get the bytes of the new image.
return image.data();
}.then(function(buffer) {
// Save the bytes to a new file.
var file = new Parse.File("image.jpg", { base64: data.toString("base64"); });
return file.save();
});
we getting error like this

There's a repeated syntax mistake at the end of each function parameter to then.
The syntax is:
somePromise.then(function() {
// success
}).then(function() { // your code says '}.' instead of '}).'
// success
});
There's an optional error function callback as second param:
somePromise.then(function() {
// success
}).then(function() {
// success
}, function(error) {
// error
});

You are missing the close parentheses for each promise callback. Your code should be this :
var url = file.url();
Parse.Cloud.httpRequest({ url: url }).then(function(response) {
// Create an Image from the data.
var image = new Image();
return image.setData(response.buffer);
}).then(function(image) {
// Scale the image to a certain size.
return image.scale({ width: 64, height: 64 });
}).then(function(image) {
// Get the bytes of the new image.
return image.data();
}).then(function(buffer) {
// Save the bytes to a new file.
var file = new Parse.File("image.jpg", { base64: data.toString("base64"); });
return file.save();
});

Related

Weird response received using Promise

vm.imageR = $resource("", {}, {
getFile: {
url: '/api/imager/:fileId',
method: 'GET',
transformResponse: function(data, headersGetter) { return { data : data }},
isArray: false,
params: {
fileId: '#fileId'
}
},
...
This is what I receive:
"�PNG
IHDRX�7�"�PLTE���V�3R�-���O�(��������������S�/���P�*��h�H��������θ������׫����奥���ᴴ�����ށ��򿿿���O�E������...
How to correctly parse the image to display as image in HTML (set as src in image)?
If you really have to load the image this way, you will have to base64 the image data being returned on the server side and append that string on your img src.
// in this format
var imgData = "data:image/png;base64,"+theBase64Data;
Otherwise you will have to use an image tag to perform the request.
var img = document.createElement("img");
img.src = '/api/imager/'+fieldId; // whatever the fieldId is
// append it to the dom.
The second option make more sense since you are getting the image from the server anyway, why base64 it?
It's weird, but this was the only change that worked:
Before:
vm.getFile = function (fileId) {
return vm.imageR.getFile({ fileId: fileId });
};
Now:
vm.getFile = function (fileId) {
var retVal = vm.imageR.getFile({ fileId: fileId });
return retVal;
};
Really weird. :)

AngularJS : Return response of a promise - ie image upload THEN submit a form

I'm trying to understand promises and $q in AngularJS. I'd like to chain 2 functions, and execute them in order. The first is a file upload, and can take a while, so I need to wait for it to be executed before creating a DB record for it.
I was originally using angular 1.3, hence the .success and .error methods.
Here's the code:
//image upload function
$scope.imageUpload = function(){
return $q(function (resolve, reject) {
var fd = new FormData();
fd.append("file", $scope.imageFile);
var data = fd;
var url = 'http://myApiUrl';
var postObject = {
method: 'POST',
url: url,
data: data
}
$http(postObject)
.success(function(response) {
return response;
}).error(function(response) {
return response;
});
})
}
// create a DB record
$scope.recordCreate = function(previousResponse){
return $q(function (resolve, reject) {
// does stuff with previousResponse, and creates a db record
})
};
// do functions in order
$scope.imageUpload().then(
$scope.recordCreate(response)
);
Not only am I getting the error
ReferenceError: response is not defined
(in relation to that last line, $scope.recordCreate(response)), but also the second function is executing BEFORE the first!
I have tried to follow the docs here https://docs.angularjs.org/api/ng/service/$q but in my example I can't get my first function to return a response to the 2nd. Does anyone know why?
You should use .then() instead of .success() to return your promise which you can then act upon and call the subsequent method.
Also, I'm curious as to why you wouldn't just update the DB server-side on your file-upload call.
no need to use $q to execute http requests in order. use promise chains to call the request after another
$scope.imageUpload = function() {
var fd = new FormData();
fd.append("file", $scope.imageFile);
var data = fd;
var url = 'http://myApiUrl';
var postObject = {
method: 'POST',
url: url,
data: data
}
return $http(postObject)
}
$scope.recordCreate = function(previousResponse) {
var url = 'db_url';
var postObject = {
method: 'POST',
url: url,
data: previousResponse
}
return $http(postObject)
};
$scope.imageUpload()
.then(function(response) {
return $scope.recordCreate(response.data)
})
.then(function(response) {
console.log(response.data);
})

Parse: using httpRequest to load image

I'm trying to load an image using Parse.Cloud.httpRequest promise inside of one beforeSave trigger, but apparently this promisse is not called. The error callback is called, but the error message is always empty.
Is possible do it into a beforesave trigger? Or maybe it's happening because of that i'm doing this inside of foreach?
The message "pablo# after load imageUrl" don't appears in Parses log, and the message "error when save user picture>>>" appears, but the error.text is empty
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey();
response.success();
var found = false;
console.log(request.object.dirtyKeys());
for (dirtyKey in request.object.dirtyKeys()) {
if (request.object.dirtyKeys()[dirtyKey] === "imageurl") {
found = true;
Parse.Cloud.httpRequest({
url: request.object.get("imageurl")
}).then(function(response) {
console.log("pablo# after load imageUrl");
var image = new Image();
return image.setData(response.buffer);
}).then(function(image) {
return image.data();
}).then(function(buffer) {
var base64 = buffer.toString("base64");
var fileTitle = request.object.id + ".png";
console.log(fileTitle);
var file = new Parse.File(String(fileTitle), { base64: base64 });
return file.save();
}).then(function(file) {
request.object.set("profileImage", file);
console.log('success');
response.success();
}, function(error) {
console.error(error);
response.error("error when save user picture>>> " + error.text);
});
}
}
if(!found){
response.success();
}
});
This is all doable with just a few improvements to the code: (1) don't call success() straight away or nothing at all will happen, (2) no need to loop dirty keys, since we're just checking for existence of one of them, (3) your code assumes that image.setData() returns a promise fulfilled by the image data: the docs are unclear about this but imply otherwise, (4) finally, let's factor the image stuff into a single, promise returning function so its easier to see what's happening...
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
fetchAndSaveUserImage(request.object).then(function() {
response.success();
}, function(error) {
response.error(error);
});
}
function fetchAndSaveUserImage(user) {
if (user.dirtyKeys().indexOf("imageurl") == -1) { return false; }
var image = new Image(); // more like docs, so we have the image in any block below
var params = { url: request.object.get("imageurl") };
return Parse.Cloud.httpRequest(params).then(function(response) {
console.log("pablo# after load imageUrl");
return image.setData(response.buffer);
}).then(function() {
return image.data(); // this is likely the same as response.buffer, but the docs do it, so just to be certain...
}).then(function(buffer) {
var base64 = buffer.toString("base64");
var fileTitle = user.id + ".png";
console.log(fileTitle);
var file = new Parse.File(String(fileTitle), { base64: base64 });
return file.save();
}).then(function(file) {
request.object.set("profileImage", file);
return true;
});
}
Incidentally, I omitted useMasterKey since I saw nothing in the code needing more permission than what's already assumed in beforeSave of a User.

Parse Promises Multiple httpRequest Cloud Code

I'm writing an iOs app with Parse.com and Cloud Code. Actually I want to retrieve objects which contain one picture and other informations from a website and I want to add them to a class named News. When I run my code, every object is saved (in my class, one row = one retrieved object) but unfortunately the only first one has its picture saved.... Any idea ?
I made a lot of searches about promises (series / parallels) and I think the problem comes from here..
Note : don't worry about myLink, myImgLink : I put this to make my code easy to read !
Parse.Cloud.define("rajouteNews", function(request, response) {
Parse.Cloud.httpRequest({ url: 'myUrl'}).then(function(httpResponse) {
var news = [];
var NewsClass = Parse.Object.extend("news");
for (var i = 0; i < 10 ; ++i) {
var maNews = new NewsClass();
maNews.set("link", myLink[i]); // "Other informations"
maNews.set("imgLink", myImgLink[i]);
maNews.set("title", myTitle[i]);
var promises = [];
promises.push(Parse.Cloud.httpRequest({
url: $('img').attr('src'),
method: 'GET',
}).then(function(httpResponse){
var imgFile = new Parse.File("photo.jpg", {base64:httpResponse.buffer.toString('base64')});
maNews.set("image",imgFile); // The picture
return maNews.save();
}));
news.push(maNews);
}
promises.push(Parse.Object.saveAll(news, {
success: function (list) {
response.success(news.length.toString() + " ont été sauvegardées");
},
error: function (list, err) {
response.error("Error adding news");
}
}));
return Parse.Promise.when(promises);
}).then(function(bla,result){
response.success("Job done");
}, function(error) {
response.error(error);
}
);
});
Your promises array should put out of the for loop scope. Otherwise , your promise array would be assigned to be a new blank array each loop.
Parse.File would be saved automaticly when its parent do save, you don't need to save it in advance.
So I improve your code as following, try it and tell me weather it works.
Parse.Cloud.define("rajouteNews", function(request, response) {
Parse.Cloud.httpRequest({
url: 'myUrl'
}).then(function(httpResponse) {
var promises = [];
var NewsClass = Parse.Object.extend("news");
for (var i = 0; i < 10; ++i) {
var maNews = new NewsClass();
maNews.set("link", myLink[i]); // "Other informations"
maNews.set("imgLink", myImgLink[i]);
maNews.set("title", myTitle[i]);
var maNewsPromise = Parse.Cloud.httpRequest({
url: $('img').attr('src'),
method: 'GET',
}).then(function(httpResponse) {
var imgFile = new Parse.File("photo.jpg", {
base64: httpResponse.buffer.toString('base64')
});
maNews.set("image", imgFile); // The picture
return maNews.save();
});
promises.push(maNewsPromise);
}
return Parse.Promise.when(promises)
}).then(function(bla, result) {
// this function is call when `Parse.Promise.when(promises)` is done,
//I can't figure out why you take two params.
response.success("Job done");
}, function(error) {
response.error(error);
});
});

How to connect jsReport in AngularJS?

I have a problem now about JSReport.. It assumed that I already have an API...What I want now is how to link it with my Client Side which uses AngularJS.
If I use Postman it will return a pdf file which is what I want. But my problem is how to show it is my page when i post it using angularjs..
I have a code like this :
Controller
$scope.Print = function () {
authService.print().then(function(result){
var _result = result;
});
};
Service
var _print = function () {
var data = { "template": { "shortid": "byQtwHLPQ" } };
return $http.post("http://192.168.8.87/api/report", data).then(function (result) {
return result;
});
};
authServiceFactory.print = _print;
Now I have that Code and its not working... I assumed it has no return so I remove the return and just post but still it didn't work and even downloading the pdf didn't work on it.
Anyone can help Please...
Use like this one..
Controller
var parameter = { "template": { "shortid": "ZkMoslfdX" }};
PrintService.Print(parameter).then(function (result) {
var file = new Blob([result.data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
Service
var reportUrl = "http://192.168.8.87/api/report";
var _print = function (parameter) {
return $http.post(reportUrl, parameter, { responseType: 'arraybuffer' }).success(function (response) {
return response;
});
};
The main idea is that the result.data is converted into a blob and create an objectURL so that it is readable and to the object tag and $sce.trustAsResourceUrl used to trust angular to your URL
HTML
<object data="{{content}}" type="application/pdf" style="width:100%;height:80%"></object>
I refer to this post AngularJS: Display blob (.pdf) in an angular app for clarification just read that one.

Categories

Resources