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

87
Vistas
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 Respuestas
Responde la pregunta

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 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