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

88
Visualizações
Upload image to express server separately than the form

So I'm working with image upload from my React app where the backend is Node and Express. In my react component I have a form with input type file and submit button. I am trying to upload the image first ( to give the user an option to delete the uploaded image ) then submit the form with the name of the file that comes back from the image upload response. But right now I'm getting an empty object for req.body and undefined for req.files in my backend.

This is my React component with handlers:

const ImageUpload = () => {

    const handleImageUpload = ( e, idx ) => {
        const formData = new FormData();
        formData.append( 'image', e.target.files[ 0 ] );
        dispatch( uploadImage( formData ) );
    }

    const handleFormSubmit= ( e ) => {
        e.preventDefault();
    }

    return (
          <form onSubmit={handleFormSubmit} >
                 <input 
                        type="file" 
                        accept=".jpg,.jpeg,.png,.gif" 
                        onChange={( e ) => handleImageUpload( e, idx )}  
                 />

                 <button type='submit'>Submit</button>
          </form>
    )
}

This is how Redux action looks like:

export const uploadImage = ( imageData ) => async ( dispatch ) => {
    try {
        const config = {
            headers: {
                'Content-Type': 'image/jpeg'
            }
        }

        const { data } = await axios.post( '/api/campaigns/upload-image', imageData, config );

        dispatch({
            type: UPLOAD_IMAGE_SUCCESS,
            payload: data
        });
    } catch ( error ) {
        console.log(error)
    }
}

This is how the backend looks like:

app.js

const express = require( 'express' );
const PORT    = process.env.PORT || 3001;
const cors    = require('cors');
const app     = express();

app.use( express.urlencoded( { extended: true } ) );
app.use( express.json() );
app.options( "*", cors( { origin: 'http://localhost:3000', optionsSuccessStatus: 200 } ) );
app.use( cors( { origin: "http://localhost:3000", optionsSuccessStatus: 200 } ) );



router.js 

const uploadImage = asyncHandler( async ( req, res ) => {
    console.log( 'req.body: ', req.body ); // {}
    console.log( 'req.files: ', req.files ); // undefined
} );

What am I doing wrong here? Is it something like formData only works for form submissions?

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

0

On Frontend:

headers should be

headers: { 
   'Content-Type': 'multipart/form-data',
}

On Backend:

multer is a classic way of handling file uploads in ExpressJS.

var multer = require('multer');

var upload = multer({ dest: './uploads' })

controller or your service:

app.post('/upload', upload.single('image'), function (req, res) {
    console.log('body data:', req.body);
    console.log('files data:', req.files);
    res.sendStatus(200);
});
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