Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to upload and read a file with nodejs / express

Tags:

there are all kinds of posts about this, but I'm still not getting it. I want to upload a *.csv and read and process its contents.

my jade file is this

//views/import.jade extends layout block content h1= title form(action="/import", method="post", enctype="multipart/form-data")     input(type="file", name="ufile")     input(type="submit", name="Upload") 

--

I changed the code, but req.files is undefined

//routes/index.js  /* import page. */ router.get('/blah', function(req, res, next) {   res.render('import', { title: 'Import Data' }); });  router.post('/import', function(req, res) {     console.log(req.files); });   module.exports = router; 
like image 625
Simply Seth Avatar asked Aug 17 '14 00:08

Simply Seth


People also ask

How do I upload files to node JS Express server using Express fileUpload library?

Create Express Server const express = require('express'); const fileUpload = require('express-fileupload'); const cors = require('cors'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const _ = require('lodash'); const app = express(); // enable files upload app.

How do I read a file in node JS?

Node.js as a File Server To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.


2 Answers

Convert the uploaded file in to string, using

toString('utf8')

you can than make any operation on string like convert it to json using csvtojson package

Here is the sample code for uploading csv and than convert to json-

/* csv to json */  const express = require("express"),   app = express(),   upload = require("express-fileupload"),   csvtojson = require("csvtojson");  let csvData = "test"; app.use(upload());  app.get("/", (req, res, next) => {   res.sendFile(__dirname + "/index.html"); });  app.post("/file", (req, res) => { /** convert req buffer into csv string ,  *   "csvfile" is the name of my file given at name attribute in input tag */   csvData = req.files.csvfile.data.toString('utf8');   return csvtojson().fromString(csvData).then(json =>      {return res.status(201).json({csv:csvData, json:json})}) });  app.listen(process.env.PORT || 4000, function(){   console.log('Your node js server is running'); }); 

working example- csvjsonapi

like image 166
Vino Avatar answered Oct 31 '22 22:10

Vino


Hope this solves your question, this is my method to multiple upload file:

Nodejs :

router.post('/upload', function(req , res) {     var multiparty = require('multiparty');     var form = new multiparty.Form();     var fs = require('fs');          form.parse(req, function(err, fields, files) {           var imgArray = files.imatges;                   for (var i = 0; i < imgArray.length; i++) {             var newPath = './public/uploads/'+fields.imgName+'/';             var singleImg = imgArray[i];             newPath+= singleImg.originalFilename;             readAndWriteFile(singleImg, newPath);                    }         res.send("File uploaded to: " + newPath);          });          function readAndWriteFile(singleImg, newPath) {                  fs.readFile(singleImg.path , function(err,data) {                 fs.writeFile(newPath,data, function(err) {                     if (err) console.log('ERRRRRR!! :'+err);                     console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);                 })             })     } }) 

Make sure your form tag has enctype="multipart/form-data" attribute.

I hope this gives you a hand ;)

like image 43
Despertaweb Avatar answered Oct 31 '22 21:10

Despertaweb