Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Axios is sending file data as undefined to a Node server

I am trying to upload a single file, and store it in a folder in my app directory. On the frontend, I am successfully selecting a file and adding it to the state of the Uploader component. When I make the POST request to the Node route with Axios, I am getting undefined in the request body.

Here is the component:

import React, { Component } from 'react';

import axios from 'axios';

export default class SandboxGet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      file: null
    };
  }

  fileSelectHandler = event => {
    const file = event.target.files[0];
    this.setState({ file: file.name });
  };

  fileUploadHandler = () => {
    const data = new FormData();
    data.append('file', this.state.file);
    console.log(data);
    axios
      .post('http://localhost:4000/upload/', this.state.file, {
        // receive two    parameter endpoint url ,form data
      })
      .then(res => {
        // then print response status
        console.log(res.statusText);
      });
  };

  render() {
    return (
      <div className="uploaderContainer">
        <div className="uploadInput">
          <i className="fas fa-upload" />
          <button className="uploadBtn">Select Files</button>
          <input type="file" name="file" onChange={this.fileSelectHandler} />
          <div className="fileName">{this.state.fileName}</div>
        </div>
        <button className="uploadFile" onClick={this.fileUploadHandler}>
          Upload!
        </button>
      </div>
    );
  }
}

Here is the Node server:

const express = require('express');
const app = express();
const multer = require('multer');
const cors = require('cors');

app.use(cors());

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, '/storage');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage }).single('file');

app.post('/upload', (req, res) => {
  console.log(req.file); // => returns nothing
  console.log(req.body; // => returns nothing
  upload(req, res, function(err) {
    if (err instanceof multer.MulterError) {
      return res.status(500).json(err);
    } else if (err) {
      return res.status(500).json(err);
    }
    return res.status(200).send(req.file);
  });
});

app.listen(4000, function() {
  console.log('App running on port 3000');
});

I feel like I am getting close, but I am missing a big piece of the puzzle.

like image 573
maison.m Avatar asked Feb 05 '26 14:02

maison.m


1 Answers

You are sending the this.state.file. You need to send the FormData.

In your case it is .post('http://localhost:4000/upload/', data) Also, you need to send the multipart/form-data header.

const headers = {
    'content-type': 'multipart/form-data'
}

Then,

axios.post('http://localhost:4000/upload/', data, {headers});
like image 61
Aritra Chakraborty Avatar answered Feb 08 '26 03:02

Aritra Chakraborty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!