Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!