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

253
Visualizações
Nodejs : req.body is empty when i try to upload a img file using jquery - ajax

i am learning nodejs and trying to upload a image file without page reload, i'm using this code below but it does not work. Req.body is empty. Can anyone help me ?

in my ejs file:

`````````````````
<body>
<form action="/" method='post' enctype="multipart/form-data" id='form-data'>
    <input type="file" name='file' id='file' class='file'>
</form>

<script>

    $(document).on('change', '#file', function () {
        var property = document.getElementById('file').files[0]; 
        var form_data = new FormData();
        form_data.append('file', property);
        $.post({
            url: '/',
            type: 'post',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                console.log(data);
            }
        })
    })

</script>
</body>



`````````````````

This is server.js:

const express = require('express');
const app = express();
const path = require('path');
app.set('view engine', 'ejs');
app.set('views' , __dirname);
app.use(express.static(path.join(__dirname, 'public')));

app.use(express.urlencoded({ extended: true })); 

app.post('/', (req,res) =>{
   console.log(req.body)
})

app.get("/", (req,res) =>{
   res.render('main');
})
app.listen(3000);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The easiest way I know to achieve what your aiming to do is with multer.

Express doesn't easily handle files on its own, so by bringing multer in as a middleware you easily upload files. take a look at line 5 and see "dest", change that to wherever you want the files to be uploaded to

On line 12 I have added the middleware to the post route, the reason I have passed in 'file' is that the form data key for the file is 'file'

On line 13 I have change console.log from req.body to req.file as you can access the file information from there with multer

const express = require('express');
const app = express();
const path = require('path');
const multer  = require('multer')
const upload = multer({ dest: './uploads/' })
app.set('view engine', 'ejs');
app.set('views' , __dirname);
app.use(express.static(path.join(__dirname, 'public')));

app.use(express.urlencoded({ extended: true })); 

app.post('/', upload.single('file'), (req,res) =>{
   console.log(req.files)
})

app.get("/", (req,res) =>{
   res.render('main');
})
app.listen(3000);

To install multer check out the link I have added or simply type:

npm install multer

Cheers, Daniel

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