sending file name on a blank page ajax call to node - node.js

it is working fine. the only problem is after execution it keeps waiting for response after setting header.. but after a while it shows no response on page it was set also it keeps waiting.. i have tried using "res.end()" it stops the response but shows only blank page here is the code..
here is the ajax code for it
var formData = new FormData($('#cover_file_form')[0]);
$.ajax({
url: '/cropImg',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
setTimeout(
function() {
$('.container-coverscreen img').attr('src','images-esct/cropped/'+data.file_name);
},
250);
}
});
and on server side
app.post('/cropImg',function(req,res){
// get the temporary location of the file
var tmp_path = req.files.file_browse_cover.path;
gm(tmp_path)
.resize(parseInt(req.body.InputWidth), parseInt(req.body.InputHeight), "!")
.crop(255, 292, parseInt(req.body.InputLeft), parseInt(req.body.InputTop))
.write(__dirname + "/public/images-esct/cropped/"+req.files.file_browse_cover.name , function (err) {
if(err) throw err;
console.log(err);
});
res.setHeader({file_name: req.files.file_browse_cover.name});
//res.end('please stop');
})
sorry for my bad english

Try to set the status code as well:
res.setHeader("Location", "/eventapp");
res.sendStatus(302);
res.end();
But it would be easier to just use the redirect-method:
res.redirect('/eventapp');

Related

how to convert image raw data to image

I want to show user's document file which is return by spring boot api in nodejs
but the file is not showing.
Here is my code of spring boot api
httpServletResponse.setHeader("Content-Disposition", "inline; filename=" + storeDocName + "");
httpServletResponse.setContentType(fileType);
httpServletResponse.setContentLengthLong(Files.readAllBytes(file.toPath()).length);
httpServletResponse.getOutputStream().write(Files.readAllBytes(file.toPath()));
Here is my node js code
requestMethodGetForImageData: function(url, form, header) {
return new Promise((resolve, reject) => {
//SET ALL THESE PARATMETER TO MAKE REQUEST
request.get({ url: url, qs: form, headers: header }, function(error, response, body) {
var result = {
body: response.body,
header: response.headers['content-type']
};
resolve(result);
}
});
});
},
I am using request module of nodejs to send the request to spring api and in nodejs here, I am calling this request function
router.get("/loadStoreDocument", function(req, res) {
var url = httpProtocol + httpServer + servicePort + serviceUrl;
//SET HEADER
headers = {
'Authorization': "token"
};
//SET FORM DATA
form = {
account_id: "id",
token_type: "token_type",
document_child_id: "id"
};
requestHandling.requestMethodGetForImageData(url, form, headers)
.then((result) => {
res.header("content-type", result.header);
res.send(result.body);
}).catch((err) => {
console.log("ERROR IN GET STORE PROFILE");
console.log(err);
res.send(err);
});
});
But when I call this URL(loadStoreDocument) then it returns image like this
enter image description here
Response of spring api is here(image data)
enter image description here
Please help me, I search this everywhere but couldn't find any solution.
You need to set encoding: null in request.get() options.
request.get({ url: url, qs: form, headers: header, encoding: null })
From request docs:
encoding - encoding to be used on setEncoding of response data. If
null, the body is returned as a Buffer. Anything else (including the
default value of undefined) will be passed as the encoding parameter
to toString() (meaning this is effectively utf8 by default). (Note: if
you expect binary data, you should set encoding: null.)

Node file uploading using formidable not working

We want to implement a functionality to upload multiple files into ExpressJS server and return all its unique urls, by an ajax call.
Following is the sample code in my front end:
var formData = new FormData();
for (var i = 0; i < nameId.length; i++) {
if($(nameId[i])[0].files[0]){
formData.append(nameId[i], $(nameId[i])[0].files[0], $(nameId[i])[0].files[0].name);
}
}
$.ajax({
url: '/upload-files',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!');
console.log(data);
}
});
And in our router we have following code snippet to accept the request and store the file:
router.post('/upload-files',function(req, res, next){
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/uploads');
form.on('file', function(field, file) {
console.log("File incoming");
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
});
But, nothing ever happened in the router. Request is coming inside the router but after that nothing.
Is there anything wrong here? We are not getting any error in server side and in client side after long wait request is failing.
Please suggest.
Thanks
I was able to resolve it by adding & updating following code snippets:
In the upload request processing function added code :
form.parse(req);
And in the app.js updated following code snippet to:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
to (To process multipart data seperatly)
app.use(bodyParser.json())
.use(bodyParser.urlencoded());
NOTE Due to the change in parser following warning message is coming while starting the server:
body-parser deprecated undefined extended: provide extended option
My problem was solved by changing my ajax sending code as follow:-
$.ajax({
url: '/postroute',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
enctype: 'multipart/form-data',
success: function(){
console.log('Uploaded sucessfully');
}
});

Using Bulit-in Http Module instead of Request Module on Node.js

I want to send form data to web-server by using Node.js, So I use "request" module that is very famous in nodeland. And It's cool, There is no problem, But because of some reason (write-stream encoding non-supported), I have to change it to built-in module, "http".
I think beneath codes are same to post some data to web-server, When I using "request" module, There is no problem so can get 200 response, success to sending data.
But in "http" module, I got a 302 response that redirects to another page. and failed post data. I don't know what is problem with, maybe it is something URL trouble, http use 'host and path' on the other hand, request use 'url' . I don't know how can I solve this, I stucked 2 days, please let me know If you have some hints..
Thanks.
By Using "Request" Module
function postFormByRequestModule() {
request({
url: 'http://finance.naver.com/item/board_act.nhn',
headers: { 'Content-Type': 'text/plain' },
method: 'POST',
form: {
code:'000215',
mode: 'write',
title: 'This is Title',
body:'This is body'
}
}, function (error, response, body) {
if (error) {
console.log(error);
} else {
console.log(response.statusCode, response.body);
}
});
}
By Using "Http" Module
var postData = querystring.stringify({
code:'000215',
mode: 'write',
title: 'This is Title',
body:'This is body'
});
var options = {
host: 'finance.naver.com',
path: '/item/board_act.nhn',
method: 'POST',
headers: { 'Content-Type': 'text/plain', }
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
res.on('end', function() {
console.log('No more data in response.')
})
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
function postFormByBuiltInHttpModule() {
req.write(postData);
req.end();
}
The built-in http client does not automatically follow forwards, whereas the request module does (and has many other "high level" features). So if you want to continue using the built-in client, you will need to manually check res.headers.location and retry the request at that url.

How to post data using node-http-ntlm?

I am trying to figure out how to actually post data using this node module:
https://github.com/SamDecrock/node-http-ntlm
It looks like posting should be similar to:
https://github.com/SamDecrock/node-httpreq#post
But the documentation for httpreq doesnt actually show POSTing a value, I only see parameters or how to POST an entire file. Im using node and have something along these lines:
NodeClient.prototype.create = function (xml) {
var options = {
url: this.url,
username: this.user,
password: this.pw,
domain: this.domain,
headers: {
'Content-type': 'text/plain'
}
};
return new Promise(function (resolve, reject) {
httpntlm.post(options,
function (err, resp) {
if(err) {
reject(err);
}
resolve(resp.body);
});
});
};
Obviously I never send my xml object, so I need to figure out how to include this. Reading the documentation hasnt lead me anywhere to this point.
You can POST xml like this:
var httpntlm = require('httpntlm');
var xml = '<?xml version="1.0" encoding="UTF-8"?>'; // replace this with your xml
httpntlm.post({
url: "https://someurl.com",
username: 'm$',
password: 'stinks',
workstation: 'choose.something',
domain: '',
body: xml,
headers: { 'Content-Type': 'text/xml' }
}, function (err, res){
if(err) return err;
console.log(res.headers);
console.log(res.body);
});
To add content to the post, you can include the following options:
json: if you want to send json directly (content-type is set to application/json)
files: an object of files to upload (content-type is set to multipart/form-data; boundary=xxx)
body: custom body content you want to send. If used, previous options will be ignored and your custom body will be sent. (content-type will not be set)

Trying to merge pdf files in node: PDFUnite + Nodejs

I have a site on heroku, and am using the HyPDF addon which allows you to manipulate pdf's in a number ways. Specifically, I am trying to merge two pdf's that I have the URL's for.
However, it's not working. I am using request to pull the pdf files and then using request to make the call to PDFUnite. It's a bit of callback hell too, so if you have any suggestions on how to fix that, I would really appreciate it!
Thanks!
request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=4010e80d-9106-4824-95ab-799ec81c7fd0', encoding: null}, function(err, res, body) {
var pdf1 = body;
request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=28a388c6-ca0e-45a1-9aaf-9b6688c5a557', encoding: null}, function(err2, res2, body2){
var pdf2 = body2;
request.post(
'https://www.hypdf.com/htmltopdf',
{
json: {
user: HY_USER,
password: HY_PASS,
file_1: pdf1,
file_2: pdf2
}
},
function (error3, res3, body3) {
if (!error && res2.statusCode == 200) {
console.log('Public URL: ', body3.url);
console.log('Number of pages: ', res3.headers['hypdf-pages']);
}
});
})
});
/****************UDPATED*****************/
I've updated the code, using https://gist.github.com/redfield/6724717 as a guide. The difference is that code sample uses files, whereas I'm using a URL.
I've tried to modify it appropriately, but obviously something is off...If I use body or body.toString('base64') as the pdf1 and pdf2 then I get a 400 status error. Otherwise, if I use the res as the pdf files, then I get a 504 error. I'm not really sure how I should be sending in the files, so it's just guess and check. Appreciate the help!
request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=4010e80d-9106-4824-95ab-799ec81c7fd0', encoding: null}, function(err, res, body) {
var pdf1 = body;
request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=28a388c6-ca0e-45a1-9aaf-9b6688c5a557', encoding: null}, function(err2, res2, body2){
var pdf2 = body2;
var form = new FormData();
form.append('user', HYPDF_USER);
form.append('password', HYPDF_PASSWORD);
form.append('test', 'true');
// form.append('bucket', 'hypdf_test');
form.append('key', 'hypdf_test.pdf');
form.append('public', 'true');
form.append('file1', pdf1);
form.append('file2', pdf2);
form.submit('https://www.hypdf.com/pdfunite', function(err, res) {
console.log('err ', err);
// res – response object (http.IncomingMessage)
console.log(res.statusCode, res.resume());
});
})
});
UPDATE #2
I've updated the code combining my code with #remus' code below. However, I'm still getting an error - "Cannot call method 'hasOwnProperty' of null" on the request.post line. Any thoughts?
request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=4010e80d-9106-4824-95ab-799ec81c7fd0', encoding: null}, function(err, res, body) {
var pdf1 = body.toString('base64');
request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=28a388c6-ca0e-45a1-9aaf-9b6688c5a557', encoding: null}, function(err2, res2, body2){
var pdf2 = body2.toString('base64');
var form = new FormData();
form.append('user', HY_UN);
form.append('password', HY_PASS);
form.append('public', 'true');
form.append('file1', fs.createReadStream(pdf1));
form.append('file2', fs.createReadStream(pdf1));
request.post({
url: 'https://www.hypdf.com/pdfunite',
formData: form
}, function(e, r, body) {
// body should be the binary result of the merged .pdf
console.log('e', e);
console.log('body', body);
});
})
});
UPDATE 3
ERROR STACK for the request.post - I've tried a number of things, can't get rid of it. Any thoughts?
TypeError: Cannot call method 'hasOwnProperty' of null
at appendFormValue (/node_modules/request/request.js:340:17)
at Request.init (/node_modules/request/request.js:354:11)
at new Request (/node_modules/request/request.js:140:8)
at request (/node_modules/request/index.js:55:10)
at Function.post (/node_modules/request/index.js:63:12)
**at Request._callback (/server/api/emailInvoice/emailInvoice.controller.js:34:12)**
at Request.self.callback (/node_modules/request/request.js:198:22)
at Request.emit (events.js:98:17)
at Request.<anonymous> (/node_modules/request/request.js:1073:14)
at Request.emit (events.js:117:20)
at IncomingMessage.<anonymous> (/node_modules/request/request.js:1019:12)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:929:16
at process._tickCallback (node.js:419:13)
First off, the main problem is you're trying to POST binary data (.pdf) as JSON in your last POST request. I imagine that's not going to work - like maybe it expects multipart file data? Second, an easy way to fix up your callback hell is to use node-async:
var request = require('request');
var async = require('async');
async.parallel(function(callback) {
pdf1: function(callback) {
request.get({
url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=4010e80d-9106-4824-95ab-799ec81c7fd0'
}, function(err, r, body) {
callback(err, body);
});
},
pdf2: function(callback) {
request.get({
url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=28a388c6-ca0e-45a1-9aaf-9b6688c5a557'
}, function(err, r, body) {
callback(err, body);
});
},
function(err, results) {
var formData = {
user: HY_USER,
password: HY_PASS,
file_1: fs.createReadStream(results.pdf1),
file_2: fs.createReadStream(results.pdf2)
}
request.post({
url: 'https://www.hypdf.com/pdfunite',
formData: formData
}, function(e, r, body) {
// body should be the binary result of the merged .pdf
});
});
});
Notice both the fs.createReadStream from the binary data stream, and the proper url using pdfunite.
You might also want to check out the hypdf NPM module - I didn't test it out, but it might make things even easier than manually building up the request.
****UPDATE****
The problem was with using FormData(). For some reason, request.post didn't like it. I was also able to remove the callbacks by injecting the request streams directly into the form. Also note, you have to set encoding to null.
var finalpdf;
var formData = {
'user': HY_USER,
'password': HY_PASSWORD,
'test': 'true',
'public': 'true',
'file1': request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=4010e80d-9106-4824-95ab-799ec81c7fd0', encoding: null}),
'file2': request({url: 'http://www.sesamestreet.org/cms_services/services?action=download&uid=28a388c6-ca0e-45a1-9aaf-9b6688c5a557', encoding: null})
}
request.post({url: 'https://www.hypdf.com/pdfunite', encoding: null, formData: formData}, function(err, res3, body3){
finalPdf = body3.toString('base64');
});

Resources