Home > Software engineering >  Upload file with React
Upload file with React

Time:08-14

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 ?

CodePudding user response:

This is because your file is not getting forwarded from frontend use FileReader instead

<input type="submit" value="Upload File" onChange={(e) => 
setFile(e.target.files)} />

const data = new FormData();

data.append(file[0])

and then you can access the file data on file[0] index and after storing the data you can forward it to the backend

CodePudding user response:

there are some problems in your code.

first of all an upload request usually is a post type. and also you should send Content-Type header with your request. so:

Axios.post("http://localhost:3001/upload", formData {
  headers: {
    'Content-Type': 'Multipart/formData',
  },
})

when you log formData it's always empty. you can use some methods like formData.keys() or formData.values() to see inside it.

  • Related