How to read the POST data inside the template in JSREPORT - jsreport

I have the following request to the jsreport engine:
$.ajax({
method: "POST",
contentType: "application/json",
dataType: "jsonp",
url: "http://localhost:5488/api/report",
data: {
template: {
shortid: "ry6HoQRee"
},
data: {
"D": "5"
}
},
success: function (s) {
window.open("data:application/pdf,base64," + escape(s.responseText));
},
error: function (s) {
console.log(s);
}
});
However I can't find a way to read it inside the report template:
<span>{{data.D}}</span>
How do I refer to the data object that is inside the POST body

jquery doesn't support binary responses like pdf. You should rather use XMLHttpRequest:
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:5488/api/report', true)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status == 200) {
window.open("data:application/pdf;base64," + window.btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response))));
}
}
xhr.send(JSON.stringify({
template: {
shortid: 'Syeopu_xe'
},
data: {
'D': '5'
}
}))
Example of reaching data using handlebars templating engine
<span>{{D}}</span>
Additionally...
You may also take a look at jsreport official browser client library. It wraps the XmlHttpRequest calls into more elegant calls:
jsreport.serverUrl = 'http://localhost:3000';
var request = {
template: {
content: 'foo', engine: 'none', recipe: 'phantom-pdf'
}
};
//display report in the new tab
jsreport.render('_blank', request);
or in async fashion
jsreport.renderAsync(request).then(function(res) {
//open in new window
window.open(res.toDataURI())
//open download dialog
res.download('test.pdf')
});

Related

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

Global function in app express.js

Trying to use a function in app, that can be called in actions.
Put in app.locals doesn't work :
app.locals({
"form_tag" : helpers.form_tag,
"text_field_tag":helpers.text_field_tag,
sendHttpGs: function(req,res) {
var querystring = require('querystring');
var data = querystring.stringify({
idSong: req.params.idSong
});
var data = querystring.stringify({
track: req.body.track
});
var options = {
host: 'localhost',
port: 8888,
path: '/exo/playlists/searchIndex.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var reqSong = http.request(options, function(ret){
ret.setEncoding('utf8');
ret.on('data', function(chunk){
req.session.search.push(JSON.stringify(chunk));
res.render('search.ejs', {
tracks: chunk,
title: req.session.search
});
});
});
reqSong.write(data);
reqSong.end();
}
});
This part is for sending http post to a php file that gets login and search function.
Where should I put it in order to use it like
.post('/loggedin', function(req,res){
global.sendHttpGS(req,res);
})
You can attach a function to the app object via app.set(), for example so something like this in your initialization code:
app.set('sayHello', function(res) {
return "hello";
});
Then in your routes, the function will be available via req.app.settings:
req.app.settings.sayHello(res);

How to Upload images from FileReader to Amazon s3, using meteor

Im trying to build an image uploader with meteor to Amazon S3. Thanks to Hubert OG, Ive found AWS-SDK which makes things easy.
My problem is that the data uploaded seems to be corrupt. When I download the file it says, the file may be corrupt. Probably it is.
Inserting the data into an image src, does work, and the preview of the image shows up as it supposed to, so the original file, and probably the data is correct.
I'm loading the file with FileReader, and than pass the result data to AWS-SDK putObject method.
var file=template.find('[type=file]').files[0];
var key="uploads/"+file.name;
var reader=new FileReader();
reader.onload=function(event){
var data=event.target.result;
template.find('img').src=data;
Meteor.call("upload_to_s3",file,"uploads",reader.result);
};
reader.readAsDataURL(file);
and this is the method on the server:
"upload_to_s3":function(file,folder,data){
s3 = new AWS.S3({endpoint:ep});
s3.putObject(
{
Bucket: "myportfoliositebucket",
ACL:'public-read',
Key: folder+"/"+file.name,
ContentType: file.type,
Body:data
},
function(err, data) {
if(err){
console.log('upload error:',err);
}else{
console.log('upload was succesfull',data);
}
}
);
}
I wrapped an npm module as a smart package found here: https://atmosphere.meteor.com/package/s3policies
With it you can make a Meteor Method that returns a write policy, and with that policy you can upload to S3 using an ajax call.
Example:
Meteor.call('s3Upload', name, function (error, policy) {
if(error)
onFinished({error: error});
var formData = new FormData();
formData.append("AWSAccessKeyId", policy.s3Key);
formData.append("policy", policy.s3PolicyBase64);
formData.append("signature", policy.s3Signature);
formData.append("key", policy.key);
formData.append("Content-Type", policy.mimeType);
formData.append("acl", "private");
formData.append("file", file);
$.ajax({
url: 'https://s3.amazonaws.com/' + policy.bucket + '/',
type: 'POST',
xhr: function() { // custom xhr
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',
function (e){
if(e.lengthComputable)
onProgressUpdate(e.loaded / e.total * 100);
}, false); // for handling the progress of the upload
}
return myXhr;
},
success: function () {
// file finished uploading
},
error: function () { onFinished({error: arguments[1]}); },
processData: false,
contentType: false,
// Form data
data: formData,
cache: false,
xhrFields: { withCredentials: true },
dataType: 'xml'
});
});
EDIT:
The "file" variable in the line: formData.append("file", file); is from a line similar to this: var file = document.getElementById('fileUpload').files[0];
The server side code looks like this:
Meteor.methods({
s3Upload: function (name) {
var myS3 = new s3Policies('my key', 'my secret key');
var location = Meteor.userId() + '/' + moment().format('MMM DD YYYY').replace(/\s+/g, '_') + '/' + name;
if(Meteor.userId()) {
var bucket = 'my bucket';
var policy = myS3.writePolicy(location, bucket, 10, 4096);
policy.key = location;
policy.bucket = bucket;
policy.mimeType = mime.lookup(name);
return policy;
}
}
});
The body should be converted to buffer – see the documentation.
So instead of Body: data you should have Body: new Buffer(data, 'binary').

How to pass Client Side data to Server Side using Ember.js

I'm studying Ember.js myself and I'm stuck with a problem I'm creating a sample app and I need to send the client side values to Server Side but I dont know how to do that I know the traditional way like the below code
function create() {
var data = {
'EmailID': $('#emailid').val(),
'password': $('#password').val()
}
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data:data,
success: function (response) {
alert("hi");
}
});
return false;
}
but In Ember i dont Know How to do that my current code is given below
//Application
App = Em.Application.create();
//Model
App.Users = Em.Object.extend({
name: null,
password:null
});
//View
App.UserTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
App.PassTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
//controller
App.AlertController = Em.ObjectController.extend({
content: [],
username: '',
password: '',
alertDetails: function () {
var me = this;
var username = me.get("username");
var password = me.get("password");
alert('The User Name Is' + 'username' + 'And Password Is' + 'password');
}
});
App.alertController = App.AlertController.create();
I got the textbox values from alertDetails function and how can I pass them to server side
App.Record = Ember.Object.extend({
name: '',
other: ''
}).reopenClass({
records: [],
find: function() {
var self = this;
$.ajax({
url: "/api/records/",
type: "GET",
cache: false,
dataType: "json",
beforeSend: function() {
//if you want to call this often and need to clear + reload it
return self.records.clear();
},
success: function(results) {
var result;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
self.records.push(self.records.addObject(App.Record.create(result)));
}
},
error: function() {
return alert("error: failed to load the records");
}
});
return this.records;
}
});
Now that you have your model setup, you can call it from your route model hook
App.RecordsRoute = Ember.Route.extend({
model: function() {
return App.Record.find();
}
});
The find method returns an empty array right away, your template is then bound to it. When the ajax call returns w/ success and you update that array the handlebars template will update it for you w/out any DOM or jQuery glue code

Title is 'Untitled' when uploading or updating a file using Google Drive API javascript?

I have been working on G drive API and doing upload, download delete and update of files and folders using JavaScript for windows 8 . The two problems which I encountered are;
When I upload a file or folder it gets uploaded with a title "UNTITLED" , can you tell me what I am doing wrong.? my request looks like this;
WinJs.xhr ({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: { "Authorization": "Bearer " + accessToken, },
data: { "mimeType": "application/vnd.google-apps.folder", "title": "sampleFolder2" } }).then
(function (success) {
var response = JSON.parse(success.response);
},
function (error) {
console.log(error);
});
When I download a file I get an encrypted or some unique type of response like if I download an JPEG image I get JFIF in response text. Can you please tell me why ? cant I get the file downloaded to my disk..?
Here is the complete function of insertion of file using media as uploadtype.
function insertFile(accessToken) {
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg", ".txt"]);
openPicker.pickSingleFileAsync().then(function (file) {
if (file) {
var tMeta = {
title: file.name,
mimeType: file.contentType,
description: "xyz description."
};
WinJS.xhr({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file.contentType,
'Title': file.name
},
body: tMeta,
}).then(function (success) {
var response = JSON.parse(success.response);
var file1 = response;
secondRequest(accessToken, file1 , file);
}, function (error) {
var x = 4;
});
}
});
}
function secondRequest(accessToken, file1,file) {
var x = 2;
var tMeta = {
title: file.name,
mimeType: file1.mimeType,
// description: "xyz description."
};
var URL = 'https://www.googleapis.com/upload/drive/v2/files/' + file1.id + '?uploadType=media'
WinJS.xhr({
url: URL,
type: "put",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file1.mimeType,
'Title': file.name
},
body: tMeta,
data: MSApp.createFileFromStorageFile(file)
}).then(function (success) {
var secondResponse = JSON.parse(success.response);
var z = 3;
}), function (error) {
var x = 3;
}
}
If you would like to upload metadata with the file, you need to implement the multipart upload. It's explained on https://developers.google.com/drive/manage-uploads#multipart