Reputation: 385
I've finally got the jsreportonline at least generating the file. Here's my code:
request.post({
url: 'https://xxxx.jsreportonline.net/api/report',
json: true,
headers: {
"Content-Type": "application/json",
"Authorization" : "Basic "+new Buffer(username:pwd).toString('base64')
},
body: {
"template" : {'shortid" : xxxxx},
"data" : xxxx,
}
}, function(err, res, body) {
**** HERE IS THE PROBLEM ****
});
I have no clue how to write the pdf output stored within variable 'body' to a file. I've tried:
var pbs = fs.createWriteStream('./report.pdf');
pbs.write(body);
pbs.end();
I've tried:
var pbs = fs.createWriteStream('./report.pdf', {defaultEncoding: 'binary'});
... but the PDF file never is displayed properly. I know the code works because I can set an option on the call:
"options" : {
"reports" : {"save" : true}
}
... and the report is saved to my jsreportonline account and renders fine.
Thanks for any help.
Upvotes: 0
Views: 2025
Reputation: 3095
You shouldn't use the callback but rather directly pipe the stream returned from the request.post
. See this in docs here. Example:
var request = require('request')
var fs = require('fs')
request.post({
url: 'https://xxx.jsreportonline.net/api/report',
json: true,
headers: {
'Content-Type': 'application/json',
'Authorization' : 'Basic '+new Buffer('xxx:yyy').toString('base64')
},
body: {
'template' : {'shortid" : xxxxx},
'data' : xxxx,
}
}).on('error', function (err) {
console.log(err)
}).pipe(fs.createWriteStream('report.pdf'))
Upvotes: 2
Reputation: 39186
You can use 'busboy' to write the uploaded file to a file in server directory.
Saving the file:-
var
express = require("express"), os = require('os'), path = require('path'), Busboy = require('busboy'), fs = require('fs'), app = express();
app.post('/savepdf', function(req, res) {
var busboy = new Busboy({
headers : req.headers
});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log("OS tmp dir ========>" + os.tmpDir());
console.log("Base name ========>" + path.basename(filename));
var saveTo = path.join(os.tmpDir(), path.basename(filename));
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
res.writeHead(200, {
'Connection' : 'close'
});
console.log("Upload finished !!!");
res.end("Success!");
});
return req.pipe(busboy);
});
app.listen(3000);
console.log('app started ');
HTML Page used to test the file:-
<html>
<head>
<title>Post Tool</title>
</head>
<body>
<h1>Save PDF </h1>
<h2>Upload Document</h2>
<form action="/savepdf" method="post" enctype="multipart/form-data">
<input type="text" name="uploadtext" id="uploadtext" value="Good" />
Choose a file : <input type="file" name="uploadfile" id="uploadfile" multiple/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Output:-
The file has been saved successfully in temp folder (i.e. windows path below).
C:\Users\userid\AppData\Local\Temp
The file name would be same as the uploaded file name.
Upvotes: 1