Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
Getting null when I send file reactjs to express server

I am trying to send files using react js to express the server. but when I send a file from the frontend I got a null value into the server.

Frontend: I have consol log into the frontend everything is ok into the frontend.

const ProductImport = function () {
    const [file, setFile] = useState<any>();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [fileName, setFileName] = useState("");

    const saveFile = (e) => {
        setFile(e.target.files[0]);
        setFileName(e.target.files[0].name);
    };
    const uploadFile = async (e: any) => {
        e.preventDefault()
        const formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", fileName);

        console.log(file);
        console.log(fileName);

        fetch('http://localhost:5000/upload-excel', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.insertedId) {
                    alert('excel Added')
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });

    };
    return (
        <form onSubmit={uploadFile}>
            <label htmlFor="formGroupExampleInput" className="form-label">Example label</label>
            <input type="file" onChange={saveFile} />
            <button type="submit">Upload</button>
        </form>
    )
}

Backend: The problem is with the backend, I got null

//MIddleware
app.use(cors())
app.use(express.json())
app.use(cors());
app.use(fileupload());
app.use(express.static("files"));
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }));

     app.post("/upload-excel", async (req, res) => {
            const file = req.files;
            console.log(file);
        });

Frontend console:

enter image description here

Backend console:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Express by default can't parse formData, you will have to use 3rd party package like multer

Few changes you will have to make, install multer npm i multer then

const multer  = require('multer')
const upload = multer({ dest: 'path/to/save/file' })

 app.post("/upload-excel", upload.single('excel-file'), async (req, res) => {
            const file = req.file;
            console.log(file);
        });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda