how to upload and read a file with nodejs / express

Simply  Seth picture Simply Seth · Aug 17, 2014 · Viewed 35.6k times · Source

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;

Answer

Vino picture Vino · Sep 12, 2018

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