Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
take a csv file as input from user using React and send it as a post request using axios

this is my react code i get an empty result when i console.log(req.body) on my express server (like this-> { body: {} }) i should get all data inside that csv file in my server plz help, thank you in advance

import React, { useState } from 'react';
import axios from 'axios';

const Form = () => {
    const [csvFile, setCSVFile] = useState();

const sendRequst = async () => {
    try {
        const res = await axios.post('http://localhost:4040/inventory/customer-segmentation', { body: csvFile });
    } catch (err) {
        console.log(err);
    }
};

const handleSubmit = (e) => {
    e.preventDefault();
    console.log(csvFile)  (*i get this File {name: 'convertcsv.csv', lastModified: 1636535333170, lastModifiedDate: Wed Nov 10 2021 14:38:53 GMT+0530 (India Standard Time), webkitRelativePath: '', size: 3491, …}*)
    sendRequst();
};


return (
    <div>
        <form onSubmit={handleSubmit}>
            <input
                type='file'
                accept='.csv'
                onChange({(e) => {
                    setCSVFile(e.target.files[0]);
            }}
            />
            <br />
            <button type='submit'>
                Submit
            </button>
        </form>
    </div>
);
};

export default Form;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since i have done a similar task today i like to post an answer to help the future readers :) (i also use typescript, tailwindcss(for styling) on the following answer which you can ignore it if you don't use neither of tools.


you can use FormData in order to send a csv file in a post request, i think this is the simplest way to send files in a post request.

in React you can create a simple form and put an input element with the type="file" inside. so that your can then use useState hook to save it as a state. after saving the file using useState hook you can simply use

formdata.append(name, value) 

and then put the formdata inside the body of axios post request. (as a good practice write onSubmit={handleSubmit} on tag not on the submit button)

const [csvFile, setCsvFile] = useState <Blob>();

const formData = new FormData();

if (csvFile){
 formData.append('path_to_csv', csvFile);
}

const handleChange = (e:React.ChangeEvent<HTMLInputElement>) => {
    if (e.currentTarget.files) setCsvFile(e.currentTarget.files[0]);
};

const handleSubmit = (e:React.FormEvent<HTMLFormElement>) => {
 e.preventDefault();

 async function fetchData() {
 const res:any = await axios.post(
   'http://127.0.0.1:8000/end_point_name_here/',
   formData,
   );
   console.log(res.data);
  }
  fetchData();
};

  return (
      <div className="flex flex-col gap-6 justify-center items-center h-screen">
        <h1> Page Title</h1>
        <form onSubmit={handleSubmit}>
          <input type="file" accept=".csv" onChange={handleChange} />
          <button type="submit" className="bg-blue-500 px-4 py-2 rounded-md font-semibold">fetch</button>
        </form>
      </div>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda