0

I am new to both nodejs and react. I am working on sending a selected file from react(front end) to the node (back end) where I can upload the file and convert the file into json object. but when I try to access the selected file from request.body, it says the selectedFile is undefined.

Node code:

const express = require("express");
const bodyParser = require("body-parser");
const excelToJson = require("convert-excel-to-json");
const upload = require("express-fileupload");
const cors = require("cors");
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(upload());

let corsOptions = {
  origin: "*",
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.post("/upload", function(request, response, next) {
  if (request.body.selectedFile) {
    let file = request.body.selectedFile;
    let dest = __dirname + "/uploads/sample.xlsx";
    file.mv(dest, function(err) {
      if (err) {
        response.send("File not found");
      } else {
        const result = excelToJson({
          sourceFile: "sample.xlsx"
        });
        response.json(result);
      }
    });
  } else {
    response.send("File not Found");
  }
});

app.listen(4001, function() {
  console.log("App is listening at port 4001");
});

React code:

import React from "react";
import axios from "axios";
import logo from "./logo.svg";
import "./App.css";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedFile: ""
    };
    this.handleFileUpload = this.handleFileUpload.bind(this);
    this.handleUpload = this.handleUpload.bind(this);
  }

  handleFileUpload = function(event) {
    this.setState({
      selectedFile: event.target.files[0]
    });

    console.log(this.state.selectedFile);
  };

  handleUpload = function(event) {
    event.preventDefault();
    console.log(this.state.selectedFile);

    let data = {
      selectedFile: this.state.selectedFile
    };

    axios
      .post("http://localhost:4001/upload", data)
      .then(res => console.log(res))
      .catch(err => console.log(err));
  };

  render() {
    return (
      <div>
        <input
          type="file"
          name="fileSelected"
          id="fileSelected"
          onChange={this.handleFileUpload}
        />
        <button type="submit" onClick={this.handleUpload}>
          upload
        </button>
      </div>
    );
  }
}

export default App;
2
  • 1
    You can use multer module in nodejs and you use FormData in ReactJS Commented Dec 24, 2019 at 7:20
  • thank you @Mr Ken using FormData worked for me Commented Dec 24, 2019 at 7:32

1 Answer 1

1

You can't send a file to JSON dialect API. But you can base64 encode the file, send it to the server and decode there. This isn't the best way, because it will increase file size while transferring to the backend, and you will spend additional resources to encode/decode it. As another option, you can use FormData to send the file to the server. For this option you need to have multipart/form-data parser in the backend, I'll suggest you using busboy

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.