无法将文件对象从reactjs发送到Node.js

时间:2019-12-24 06:59:39

标签: javascript node.js reactjs express axios

我对Node.js都是陌生的,并且会做出反应。 我正在将选定的文件从react(前端)发送到节点(后端),在那里我可以上传文件并将文件转换为json对象。但是当我尝试从request.body访问选定的文件时,它说selectedFile是未定义的。

节点代码:

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");
});

反应代码:

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;

1 个答案:

答案 0 :(得分:1)

您无法将文件发送到JSON语言API。但是您可以对文件进行base64编码,将其发送到服务器并在其中解码。这不是最佳方法,因为它会在传输到后端时增加文件大小,并且您将花费更多资源来对其进行编码/解码。作为另一种选择,您可以使用FormData将文件发送到服务器。对于此选项,您需要在后端有multipart/form-data解析器,我建议您使用busboy