Node service: shown below are node service call where getting data from mysql query. And converting to json2csv format.
function getData(req,res){
var json2csv = require('json2csv');
var resultset = {};
resultset.data = [];
var nodeExcel=require('excel-export');
var dateFormat = require('dateformat');
var queryString = "select name ,class ,fname from details"
connection.query(queryString, function(err, result) {
if(err) {
console.log('error ',err);
resultset.success=false;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData =resultset;
res.write(JSON.stringify(resultData));
res.end();
} else {
if(result.length>0) {
for(var i=0;i<result.length;i++) {
resultset.data[i]={};
var arr=_(result[i]).toArray();
resultset.data[i].name=arr[0]!=null?arr[0]:null;
resultset.data[i].class=arr[1]!=null?arr[1]:null;
resultset.data[i].fname=arr[2]!=null?arr[2]:null;
}
resultset.success=true;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData =json2csv(resultset);
console.log("resultData",resultData);
res.write(JSON.stringify(resultData));
res.end();
}
else{
resultset.success = false;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData = resultset;
res.write(JSON.stringify(resultData));
res.end();
}
}
});
}
Controller:
getting the service response.
$scope.Details=function(data,fileName){
$http.get(Data.baseNodeService+'getData',headconfig).then(function(response,fileName){
$scope.det = response.data.data;
var element = angular.element('');
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI($scope.det),
target: '_blank',
download: 'filename.csv'
})[0].click();
});
}
On click Html Download:
<input type="button" class="bt-submit" ng-click="Details()" value="Download" />
But I am getting download output as [object Object].I want to get data from my service call and download in csv format.
You can download CSV in different ways, this below is a common way to download file
var a = document.createElement('a');
a.href = 'data:'+mimeType+';charset=utf-8;base64,' + response;
a.target = '_blank';
a.download = "name the file here";
document.body.appendChild(a);
a.click();
use the mimeType as your file type here for csv it would be attachment/csv but this won;t work on safari.
There is awseome library https://github.com/alferov/angular-file-saver You can use this.
You can call it like
function download(api, file, contentType) {
var d = $q.defer();
$http({
method: 'GET',
url: api,
responseType: 'arraybuffer',
headers: {
'Content-type': contentType
}
}).success(function(response) {
var data = new Blob([response], {
type: contentType+ ';charset=utf-8'
});
FileSaver.saveAs(data, file);
d.resolve(response);
}).error(function(response) {
d.reject(response);
});
return d.promise;
}
Also see my other answers on file download
how to export data into CSV and PDF files using angularjs
And
AngularJS - Receive and download CSV
Try this:-
/*this section for CSV*/
if(window.navigator.msSaveOrOpenBlob && window.Blob) {
var blob = new Blob([response.data.data], {type: "text/csv"});
navigator.msSaveOrOpenBlob(blob, new Date().getTime() + '.csv');
} else {
var anchor = angular.element('<a/>').css({display: 'none'});
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(response.data.data),
target: '_blank',
download: new Date().getTime() + '.csv'
})[0].click();
anchor.remove();
}
Related
My webpage provides functionallity to convert pdf to image.
For Webpage i am using Firebase Hosting and for functions obvs Functions.
But after file upload function logs error in firebase dashboard Boundary not found
Below is the code i used to upload file in html:
function uploadFile() {
var file = document.getElementById("file_input").files[0];
var pass = document.getElementById("pass").value;
console.log(file + pass);
var formdata = new FormData();
formdata.append("file", file);
formdata.append("password", pass);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "/upload");
ajax.setRequestHeader("Content-Type", "multipart/form-data");
ajax.send(formdata);
}
and this is the code of functions:
var functions = require('firebase-functions');
var process;
var Busboy;
var path = require('path');
var os = require('os');
var fs = require('fs');
exports.upload = functions.https.onRequest((req, res) => {
const busboy = new Busboy({ headers: req.headers });
const fields = {};
const tmpdir = os.tmpdir();
const uploads = {};
const fileWrites = [];
var pass = '';
busboy.on('file', (fieldname, file, filename) => {
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
const promise = new Promise((resolve, reject) => {
file.on('end', () => {
writeStream.end();
});
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
fileWrites.push(promise);
});
busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
pass = val;
});
busboy.on('finish', function () {
console.log('Done parsing form!');
console.log(pass);
console.log(uploads);
process.processCard(uploads['file'], pass, 2).then((s) => {
res.end(`
<!DOCTYPE html>
<html>
<body>
ImageConverted!!
<img src="data:image/jpeg;base64,${s}" width="90%"></img>
</body>
</html>
`);
}).catch((err) => { res.end('Error: ' + err) });
});
busboy.end(req.body);
});
What am i doing wrong ?
For multipart body it is recommended to use req.rawBody instead of req.body
https://stackoverflow.com/a/48289899/6003934
Can't download and rename a jpg image.Instead it downloads a corrupted jpg file, that if you change the extension to ".txt" you can see the path of the image in there.
The original code that I had working was the following:
function downloadImg(id){
var deferred = $q.defer();
$http({
method: 'GET',
url: API_URL + 'image/' + id
}).then(function(res){
console.log(res.data);
if(res.data && res.data.length > 0){
window.location.href = res.data;
}
deferred.resolve();
}, function(err){
console.log(err);
deferred.reject();
})
return deferred.promise;
}
So, I just want to rename the image before or after download it.
I end up with this code, that the only thing that is doing is setting the image path into a file or in this case [object Object] in the file(depending on the code I'm using I endup with object... or the image path...).
function downloadImg(id){
var deferred = $q.defer();
$http({
method: 'GET',
url: API_URL + 'image/' + id,
responseType: 'blob'
}).then(function(res){
console.log(res.data);
var file = new Blob([res], {type: 'image/jpeg;charset=UTF-8'});
var fileURL = URL.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = "newName.jpg";
a.click();
deferred.resolve();
}, function(err){
console.log(err);
deferred.reject();
})
return deferred.promise;
}
Also I tried setting responseType:'arraybuffer'and blob as well as tried to using FileSaver.saveAsand tried to create a blob from base64 found at : http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
My image url is something like (I replace some things with "personalName" because I can't share the image): https://personalName.personalName.com/component/get?id=cbd6a354-1700-11e8-b451-0a540af4044a&username=personalName&apiKey=a393ceba-1350-11e6-9382-f23c91df2143
I expected to have the original jpg image, but with the new name.
Thanks.
i am new in nodejs . i tried the below code for retriving json object. but i can't retrive a single data from json object
My code is
function getData(){
var http = require('http');
var qs = require('querystring');
var str = '';
var options = {
host: '192.168.1.16',
port: 8080,
path: '/courseapi/view'
};
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
console.log(str[0]._id);
});
}
var req = http.request(options, callback).end();
};
i tried this str[0]._id but it return undefined
Try:
response.on('end', function () {
str = JSON.parse(str);
console.log(str);
console.log(str[0]._id);
});
When I sending post request by this code:
var data = '{data: 1111}'; // = JSON.stringify(message);
console.log('NotifySplitter: ' + data);
var options = cfg.splitterOptions;
options.headers['Content-Length'] = Buffer.byteLength(data)
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
... and getting data by this code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(request, response){
var query = request.body;
console.log(request.body);
response.end();
});
request.body contains:
{'{data: 1111}': ''}
instead expected {data: 1111}. Is it normal? How to get normal data without replacing external {} in origin data before post?
You have to set up an appropriate content-type. If you're sending json, add options.headers['Content-Type'] = 'application/json' to your request.
Also, {data: 1111} is not a JSON, it's JSON5. While it's better all around, it's not supported by default express.bodyParser(), so watch out for that.
I'm using the following code to send a session description (tiny JSON code - http://www.ietf.org/rfc/rfc2327.txt).
function sendMessage(message) {
var msgString = JSON.stringify(message);
console.log('C->S: ' + msgString);
path = '/message?r=67987409' + '&u=57188688';
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send(msgString);
}
I'm not sure how to go about retreiving the JSON on my Node.js server.
Here's a code that can handle POST request in node.js .
var http = require('http');
var server = http.createServer(function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = JSON.parse(body);
// POST is the post data
});
}
});
server.listen(80);
Hope this can help you.