Search code examples
reactjsformsupload

Upload file with React


I want to make a simple file upload form on the front end. Then, on the backend, I would pass the information about that file to an API.

Here is my front-end code where I call a specific function on the back end and pass the data:

import React from 'react';
import Axios from 'axios';

const Upload = () => {
  // a local state to store the currently selected file.
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleSubmit = async (event) => {

    event.preventDefault()
    
    //Got all the Infos about my file
    console.log(selectedFile)
    
    const formData = new FormData();
    formData.append("selectedFile", selectedFile);

     //Empty result
    console.log(formData)

    Axios.get("http://localhost:3001/upload", {
      //I will pass the data to a function in the backend
      params: {
        data: formData,
      },
      
    })
      .then((Response) => {
        console.log(Response)
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  const handleFileSelect = (event) => {
    setSelectedFile(event.target.files[0])
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileSelect}/>
      <input type="submit" value="Upload File" />
    </form>
  )
};

export default Test

On the back-end side, a route call the method

router.get('/upload?', Upload);

Then finally the function in the backend to process

const ApiProcess = (req, res) => {
  var axios = require('axios');
  var data = req.query

  console.log(req.query)
 
//All the API Stuff
  
}

But the problem is that I receive empty data in the Backend. What's wrong with my code?

Thanks

EDIT

On backend side I use multer and add 'app.use(multer().any())' on top of index file. That help cause now I cant access in backend to a simple formData. Now my function that receive the data log this '[Object: null prototype] {}'

Any idea ?


Solution

  • Ok I got the solution. I missed a piece of middleware to process Multipart/formdata on Express Side :

    const router = express.Router();
    const multer = require("multer");
    //Set the destination folder and Naming of the file that is upload
    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
          cb(null, 'uploads/')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
      })
      
      const upload = multer({ storage: storage })
    
    Then I process the formData with the files
    router.post('/upload', upload.array("file"),Upload);
    
    
    

    Thanks a lot for your help