soccerway
soccerway

Reputation: 11931

How can we receive a csv file in server side react hooks web app

In react hooks web app, how can we receive a csv file in the server side. The below is not working as I am getting the file undefined in server side. Could someone please advise ?

server.js

const multer  = require('multer');
const bodyParser = require("body-parser");
const path = require('path');

app.use(express.static(path.join(__dirname, 'public')));

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/csv')
  },
  filename: function (req, file, cb) {
    var ext = file.originalname.split('.').pop();
    cb(null, file.fieldname + '-' + Date.now() + '.' + ext);
  }
})

var upload = multer({ storage: storage });

    app.put('/service/managenominees', upload.single('file'), async (req, res, next) => {

     // csv file has two columns named Name, Email, I would like to receive value from those..
    
      const data = req.file;
      try {
        if(req.body.file){
          var name = req.file.Name;
          var email = req.file.Email;
        }
        var nomineeData = {userName: name, userEmail: email};
        res.status(200).send(nomineeData);
      } catch (e) {
        res.status(500).json({ fail: e.message });
      }
    });

manageNominee.js

import React, { useRef, useEffect, useState } from "react";
import Axios from "axios";


const ManageNominees = () => {
    const [uploadFile, setUploadFile] = React.useState();
    const [csvData, setCsvData] = useState([]);


    const onChangeCsv = (e) => {
        setCsvData(e.target.files[0]);
    }

    const submitForm = (data) => {
        const dataArray = new FormData();
        dataArray.append("uploadFile", data);
        Axios.put("http://localhost:8000/service/managenominees", dataArray, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then((response) => {
        // successfully uploaded response
      })
      .catch((error) => {
        // error response
      });

    };


    return (
        <div>
            <form onSubmit={submitForm} encType="multipart/form-data">
                <h1>Upload Data</h1>
                <input type="file" name="csvfile" onChange={onChangeCsv}/>
                <button>Submit</button>
            </form>
        </div>
    )
}

export default ManageNominees

enter image description here

Upvotes: 0

Views: 316

Answers (1)

Bharath
Bharath

Reputation: 400

There are two issues:

  1. HTML attribute and the mutler upload option are different.
  2. File values cant be accessed directly either convert the buffer and read the content or read the file (below code reads the file).
const multer  = require('multer');
const bodyParser = require("body-parser");
const path = require('path');

const csv = require('csv-parser');
const fs = require('fs');

...

app.put('/service/managenominees', upload.single('csvfile'), (req, res, next) => {
    console.log(req.file);
    fs.createReadStream(req.file.path)
        .pipe(csv())
        .on('data', (data) => results.push(data))
        .on('end', () => {
            console.log(results);
            // Result would be array as its CSV, iterate over the array and to get username and email id.
            res.status(200).send(results);
        });
});

Note: Code does not handle if the file does not exist.

Upvotes: 1

Related Questions