Upload Excel file and download from mysql using Node js - mysql

I want to upload Excel sheet and after submit that excel sheet need to insert data into mysql database and same sheet which we upload need to download.
I have tried below code:
Node Service-
function getDetails(req, res) {
var sampleFile, fileInfo = {};
var post = req.body;
var ID= post.id;
var name=post.name
if (!req.files) {
res.send('No files were uploaded.');
return;
}
sampleFile = req.files.fileInputXLSX;
console.log("req.body -- ",req.body);
console.log("Uploaded -- ",sampleFile);
// Get file attributes
var fileId = req.body.fileId;
var fileExtn = sampleFile.name.split(".").pop();
var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
var uploadFileName = extractedFilename+'_'+fileId+'.'+fileExtn;
console.log("uploadFileName -- ",uploadFileName);
fileInfo = {
"name": uploadFileName,
"mimetype": sampleFile.mimetype
}
sampleFile.mv(__dirname+'/Myuploads/Details/'+uploadFileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
// Update file info
var queryString = "INSERT INTO 'details'('id','name') VALUES ('" + ID + "','" + name + "')";
connection.query(queryString, function(err, result) {
if (!err){
var response = [];
response.push({'result' : 'success'});
if (result.length != 0) {
response.push({'data' : result});
} else {
response.push({'msg' : 'No Result Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
}
});
}
Controller.js
$scope.MyFunction=function(){
var excelForm = new FormData();
excelForm.append('fileInputXLSX', document.getElementById("fileInputXLSX").files[0]);
console.log("---- excelFile : ", document.getElementById("fileInputXLSX").files[0]);
// End : Get File
$http.post(Data.baseNodeService + "getDetails", {
"newProtocolObj": $scope.newProtocolObj
},headconfig).success(function(data, status, headers, config) {
console.log('Details: success');
excelForm.append('fileId', data);
jQuery.ajax({
url: data.baseNodeService + "getDetails",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: excelForm,
success: function(data) {
console.log("---- upload response : ", data);
$scope.goToTfilePage();
}
});
// End : Upload File
}).error(function(map_data, status, headers, config) {
console.log('Details: error');
console.log('status: ', status, '\nmap_data: ', map_data, '\nconfig: ', config);
});
}
Message is coming in console: No file is uploaded.
Please help with the same.It is not upload the file.It is not able to read the response from node service.
I am new in this help in which manner i need to write.
Edit:I am able to upload the file but how to insert into mysql database??

Related

Generating a PDF file using data from MySQL database in Node js

I am trying to generate a PDF file using the data stored in the Mysql database using Node js, Pdfkit and pdfkit-table. I need to print the records in database to a table in the PDF document.
The below code generates an empty PDF file. Please help me to solve the problem of why it does not generate a PDF file with data.
This is index.js file.
var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var orm = require('orm');
var PDFDoc = require("pdfkit-table");
router.use(orm.express("mysql://root:#localhost:/kirula_fashion", {
define: function (db, models, next) {
models.news = db.define("ledger", {
id : String,
date : String,
description : String,
debit : String,
credit : String,
});
next();
}
}));
router.get('/', function(req, res, next) {
var result = req.models.news.find({
}, function(error, news){
if(error) throw error;
res.render('index', { news:news, title: 'Generate PDF using NodeJS'
});
});
});
router.get('/pdf', function(req, res, next) {
var id = req.query.id;
const doc = new PDFDocument();
const docTable = new PDFDoc();
var result = req.models.news.find({id: id}, function(error, newspost){
if(error) throw error;
else{
if(newspost.length>0){
for(var i=0; i<newspost.length;i++){
var date = newspost[0]['date'];
var description = newspost[0]['description'];
var debit = newspost[0]['debit'];
var credit = newspost[0]['credit'];
var table = {
title: "Ledger records",
subtitle: "May - 2020",
headers: [
{ "label":"Date", "property":"date", "width":100 },
{ "label":"Description", "property":"description", "width":100 },
{ "label":"Debit", "property":"debit", "width":100 },
{ "label":"Credit", "property":"credit", "width":100 }
],
datas:
[
{ "date":date, "description":description, "debit":debit, "credit":credit},
{
"renderer": "function(value, i, irow){ return value + `(${(1+irow)})`; }"
}
],
};
docTable.table( table, {
width: 300,
});
}
}
}
var title = "Ledger for May 2020";
var filename = encodeURIComponent(title) + '.pdf';
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"');
res.setHeader('Content-type', 'application/pdf');
doc.pipe(res);
doc.end();
});
});
module.exports = router;
I encounter the same issue with datas options, however with rows options pdfkit-table work nicely, maybe mapping from [{..},{...}] to [[..],[...]] then use rows option

Delete Objects in Bucket with jQuery

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

How to fetch particular data in column from JSON with keys

I am not sure how to fetch particular data in column from JSON with the help of keys. From ajax request i am getting data from the server but i want to store it in sqlite as the columns in server
$("#xxx").click(function()
{
var e = $("#mob").val();
var p = $("#key").val();
myDB.transaction(function(transaction)
{
transaction.executeSql('CREATE TABLE IF NOT EXISTS User_data (data)', [],
function(tx, result)
{
navigator.notification.alert("table created");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
$.ajax
({
url: "http://192.168.1.4/sms/android.php",
type: "GET",
datatype: "json",
data: { type:'login', phone: e, name: p },
ContentType: "application/json",
success: function(response)
{
var valuesInArray = JSON.stringify(response);
var user_data = JSON.parse(valuesInArray);
for(var item in user_data.Users)
{
myDB.transaction(function(transaction)
{
transaction.executeSql('INSERT INTO User_data (id,date_closed) VALUES (item.id,item.date_closed)', [],
function(tx, result)
{
navigator.notification.alert("data inserted");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
}
},
error: function(e)
{
alert('Got ERROR: ' + JSON.stringify(e));
}
});
});
here is the image of the data i am getting from the server
DATA IN ALERT BOX
here, i want to fetch each column in the database.
Thankx in advance.
<?php
header('Access-Control-Allow-Origin:*');
pg_connect("host=localhost port=5432 dbname=** user=** password=***");
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$mobile = $_GET['phone'];
$key = $_GET['name'];
$query = "select * from crm_lead where phone='$mobile' and id='$key'";
$result = pg_query($query);
while($myrow = pg_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('Users' => $recipes));
echo "'".$output."';";
}
}
else
{
echo "invalid";
}
pg_close();
?>
Why can't you use the response object directly since it's already a Json object?
var users = response.Users;
for(var i=0; i < users.length;i++)
{
var id = users[i].id;
//do something with id
}
$.ajax
({
url: "http://182.70.240.81:82/sms/android.php",
type: "GET",
datatype: "json",
data: { type: 'login', phone: 9770869868, name: 14 },
ContentType: "application/json",
success: function (response) {
var simpleJson = JSON.parse(response);
var shortName = 'db_test';
var version = '1.0';
var displayName = 'Test Information';
var maxSize = 65536; // in bytes
var db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(function (txe) {
txe.executeSql('DROP TABLE User_data');
txe.executeSql('CREATE TABLE User_data(id INTEGER,date_closed TEXT)');
db.transaction(function (txe1) {
for (var i = 0; i < simpleJson.Users.length; i++) {
txe1.executeSql('INSERT INTO User_data (id,date_closed) VALUES (' + simpleJson.Users[i].id + ',"' + simpleJson.Users[i].date_closed + '")', [],
function (tx, result) {
alert("data inserted");
},
function (error) {
alert("error, table exists");
});
}
});
});
}
});
Remove Single Qoutaion from your json:

Change file name of toStream() in node.js html-pdf npm module

I am trying to change the file name of the pdf generated by the npm module html-pdf.
The issue is I do not want to save a copy of the pdf, just stream it to an email service ( mailgun) and then send it off. I have everything working but when I receive the email the file has a default name that I want to change. Does anyone have any experience trying to do this?
Thanks
var pdf = require('html-pdf');
var Mailgun = require('mailgun-js');
pdf.create(result).toStream(function(err, stream) {
var self = this;
if (err) return console.log(err);
//set mailgun parameters
var mail_data = {
from: 'emailtosendto#email.com',
to: 'sendingemail#email.com',
subject: 'subject line',
html: result,
attachment: stream
}
//send email
mailgun.messages().send(mail_data, function (err, body) {
if (err) {
res.render('error', { error : err});
console.log("got an error: ", err);
}
else {
console.log(body);
res.send('ok');
}
});
});
var pdf = require('html-pdf');
var Mailgun = require('mailgun-js');
pdf.create(result).toBuffer(function(err, buffer) {
var self = this;
if (err) return console.log(err);
var attch = new mailgun.Attachment({data: buffer, filename: 'myattach.pdf'});
//set mailgun parameters
var mail_data = {
from: 'emailtosendto#email.com',
to: 'sendingemail#email.com',
subject: 'subject line',
html: result,
attachment: attch
}
//send email
mailgun.messages().send(mail_data, function (err, body) {
if (err) {
res.render('error', { error : err});
console.log("got an error: ", err);
}
else {
console.log(body);
res.send('ok');
}
});
});
From https://github.com/bojand/mailgun-js#attachments

Node.js : Write new data to an existing json file

I'm trying to add data to an existing json file (codes below). When I access the locahost, the new piece of data shows up, however, when I check the data (users.json), the new piece of data (i.e. user4) isn't there.
Does anyone know what's wrong with the code? Thank you!
var express = require('express');
var app = express();
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end( JSON.stringify(data));
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
EDIT:
I added fs.writeFile(...) (codes below). After running the code, the only content of the uers.json file is:utf8
var express = require('express');
var app = express();
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
// res.end( JSON.stringify(data));
data = JSON.stringify(data);
fs.writeFile(__dirname+"/"+"users.json", "utf8", function(err,data){
if (err){
console.log(err);
};
res.end(data);
});
});
})
To write to a file you should use fs.writeFile.
fs.writeFile(__dirname + "/" + "users.json", user["user4"], 'utf8', function()
{
// do anything here you want to do after writing the data to the file
});
I have passed data to writeFile so that it may write the information in data variable to JSON
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
data = JSON.stringify(data);
fs.writeFile(__dirname + "/" + "users.json", data , 'utf8', function(err,data) {
if (err){
console.log(err);
};
res.end(data);
});
});