简体   繁体   中英

Could not send file object from reactjs to nodejs

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM