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?
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);
});